Welcome to the Treehouse Community
Looking to learn something new?
Question about variables in "for" loops
The example in Logic in Python: Around and Around reads:
my_list = ['hello', 'how', 'are', 'you'] for word in my_list: print(word)
My question is: how does Python understand that "word" is a variable that applies to the items in the my_list set? Does it matter what you put there? Is it just a stand-in that Python understands? That is, Python can see that my_list is a list of things, a list of strings, even. And so it just assumes that when you say "for foo in my_list" that whatever it is in my_list is a list of foos? Or is there some underlying syntax I'm missing?
Gianmarco Mazzoran22,052 Points
my_list = ['first', 'second', 'third'] for thing in my_list: print(thing)
the word "thing" retrieve the same result of your word "word" in the for loop. It's just naming convention. Perhaps if have a list of books my for loop would look like something like this:
for book in books: print(book)
with variables it works the same way, but returns the value stored inside the variables:
var1 = "Hi" var2 = "how" my_list = [var1, var2] for thing in my_list: print(thing)
the output for the loop above would be:
For Python doesn't matter what's inside your list. It's assume that is a iterable object and with the for loop go trougth every item inside your list.
Here's the documentation about it.