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 trialEnzo Cnop
5,157 PointsMystery Variable 'word' in first example.
In the first example of a simple 'For loop', Kenneth writes the following:
- my_list = ['hello', 'how', 'are', 'you']
- for word in my_list:
- print(word)
My question is when is the variable 'word' in line two defined? Does Python already know that the list, 'my_list', contains whole words? This is done later with 'number' as well. Does that mean I just set 'for word' or 'for number' based on whether my list contains letters or integers accordingly?
2 Answers
bryonlarrance
16,414 PointsPython knows that the word that follows 'for' in a for loop is the variable. It could be anything - the letter i, cookie, whatever. . . literally whatever. :)
bryonlarrance
16,414 PointsYep! So the for loop could be
for boogers in my_list:
or
for anything in my_list:
ryan smith
687 Pointsbut does that make everything in my_list a booger?
Enzo Cnop
5,157 PointsEnzo Cnop
5,157 PointsI still don't really understand how this works. So any word after 'for' is going to be read/set as a variable? Does this only work because 'word' is set between the 'for' and 'in' operators // is attached to 'my_list'?