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 Introducing Lists Using Lists Mutability

Confuse about the for loop

for item in inventory.copy(): inventory.remove(item)

Do all the list items go into item? Why wouldn't it be item.remove(inventory)?

2 Answers

andren
andren
28,558 Points

Do all the list items go into item?

Yes, they do. A for loop creates a variable (named item in the above example) and then assigns it items from a list you specify (a copy of inventory in the above example). The way it does this is that it first assigns the first item of the list to the variable, then runs the code. Then after running the code it assigns the second item from the list to the variable, and then runs the code again. It continues this cycle until it has gone though all of the items in the list and then it stops the loop automatically.

That means that this code:

names = ["Tom", "Mary", "John"]
for name in names:
    print(name)

Would operate in the same way as the following code:

names = ["Tom", "Mary", "John"]
name = names[0] # Pull out the first item from names
print(name)
name = names[1] # Pull out the second item from names
print(name)
name = names[2] # Pull out the third item from names
print(name)

Both of those code examples will result in the same thing, but the first example is obviously a lot more succinct, and more dynamic since you don't need to know the size of the list in advance.

Jesse Davidson
Jesse Davidson
647 Points

Your explanation is perfect. Thanks dude.