Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

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?

2 Answers

Gianmarco Mazzoran
Gianmarco Mazzoran
22,052 Points

Hi,

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:

Hi
how

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.

thanks!