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,343 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.