Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Logic in Python Around and Around

Arikaturika Tumojenko
Arikaturika Tumojenko
8,897 Points

When did we define the variable "word"?

When did Kenneth define the variable word so python knows we are talking about a variable when we ask it to print the list elements? I'm very confused as these concepts are not being explained.

2 Answers

andren
andren
28,558 Points

The for loop itself is the thing that created the word variable.

The way a for loop works is that each time it runs it pulls out an item from a list you specify and assigns it within the loop to a variable you specify.

So for word in my_list is a loop that says take the items from a list called my_list, and pull them out one by one and assign them to the variable word.

The first time the loop runs your code word will contain the first item of my_list, the second time the loop runs it will contain the second item of my_list and so on, until it has run through all of the items.

Arikaturika Tumojenko
Arikaturika Tumojenko
8,897 Points

Thank you for the explanation. Python is so strange, compared to Java Script, for example.

andren
andren
28,558 Points

While I won't disagree that Python is somewhat unique, this type of for loop is actually pretty common and found in quite a few languages. JavaScript ES6 also supports this type of loop, just using the word of instead of in.

Like this:

myList = ["hello", "how", "are", "you"];
for (var word of myList) {
    console.log(word);
}

That code would print out the items of the myList array just like the Python code in the video.

Arikaturika Tumojenko
Arikaturika Tumojenko
8,897 Points

Oh, my mistake, I was referring to declaring variables in Javascript, where things are more strict.