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

Problem --> for name in names:

So when Kenneth does @ 6:00

names = ['Kenneth, 'Amy', 'Andrew'] 
for name in names:

I saw in some post that python assumes name as a variable so we do not need to define it. However this also must mean that Kenneth, Amy, and Andrew are all under the variable of both name and names because once he prints it out as a loop it lists all three meaning all are under variable names and variable name How is this possible?

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! Yes, this is correct. The name variable you can think of as a local variable for the duration of the loop. Once the loop ends the name will go out of "scope" and no longer be available. However, names is a list of individual names. What this loop is saying is "for each individual item in the list assign that item to the variable name then continue to the next item until the list is complete".

So if you had:

for name in names:
     print(name)

It would print Kenneth, Amy and Andrew each on a new line. Because the first iteration of the loop the name is set to the first item in the list and we print the value of name. Then it goes to the next item in the list which will have name set to "Amy". And then we print that name. And this continues until the list has been completely exhausted.

Hope this helps! :sparkles: