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 trialArikaturika Tumojenko
8,897 PointsWhen 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
28,558 PointsThe 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
8,897 PointsOh, my mistake, I was referring to declaring variables in Javascript, where things are more strict.
Arikaturika Tumojenko
8,897 PointsArikaturika Tumojenko
8,897 PointsThank you for the explanation. Python is so strange, compared to Java Script, for example.
andren
28,558 Pointsandren
28,558 PointsWhile 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 wordof
instead ofin
.Like this:
That code would print out the items of the
myList
array just like the Python code in the video.