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

Thelma Boamah
Thelma Boamah
15,726 Points

Why don't you have to set word as a variable before you can use it in the for loop to print(word) in my_list?

In JavaScript for example, you'd have to set word to an index value and loop through that index value. Does Python just know to do this automatically? Apologies if this is explained later in the video.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The for...in statement takes care of the assignment for you. It says "for each item in the container (my_list), assign the item to the variable 'word' then run the code block. Once complete, repeat the loop with the next item in container assigned to 'word'"

Thelma Boamah
Thelma Boamah
15,726 Points

Thanks for clearing that up, Chris.

Hi Chris,

If I try below codes:

my_list = [1, 2, 3, 4]

for list in my_list:

print(list)

but , as my understood above your reply, if I type "list", it should return

list

[1, 2, 3, 4]

but it actually just return

5
Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Sky, it uncertain the exact intention of your code due to the indention issues. Another issue is using the built-in name list as a variable name. Using "list" as a variable name overwrites the object in the local name space removing the list functionality.

If I reformat you code, I get

>>> my_list = [1, 2, 3, 4]
>>> for item in my_list:
...     print(item)
...
1
2
3
4
>>> item
4

Notice that item retains the value from the last iteration of the loop

I cannot figure out how you got the result "5". A more explicit and accurate screen capture would be needed.