Python Introducing Lists Using Lists Mutability

At the very end of the video where you show us the issue with using the remove method while looping through confused me.

From what I know when you remove something from an array in java everything gets shifted to the left 1 so therefore if you remove something on index 0 unless you subtract 1 from the current index you are going to remove it will skip over what was just shifted down.

But when you copied the inventory and then removed from the master inventory I got very confused as to why that works.

3 Answers

Kyle Petran
Kyle Petran
5,017 Points

Okay well in Python, everything to the right of the element you removed gets shifted to the left one as you stated. However I believe while he is looping through his List the item index is remains the same. It'll be easier to demonstrate.

so we start just as he started:

inventory = ["apple", "orange", "pizza", "burger"]
for item in inventory:

Now logically our item at index 0 is removed:

inventory = ["orange", "pizza", "burger"]

here is where I think you were tripped up. Instead of removing the foremost element, the item variable now goes from inventory[0](which is currently "orange") to inventory[1](which is currently "pizza") so the result it:

inventory = ["orange", "burger"]

If this isn't clear please let me know.

That explains it very well, thank you for your time and keep on learning!

Eswar Ambati
Eswar Ambati
717 Points

could u please explain the last part of your answer I dont understand it of the item goes from 0 to 1

Gali Berkowiz
Gali Berkowiz
2,082 Points

I understand the problem, but I don't understand how using .copy is fixing it?

Can you explain for me the difference between:

a = [1,2,3] for b in a: a.remove(b)

and the syntax:

a = [1,2,3] for b in a.copy(): a.remove(b)

I saw it has difference results.

thanks for the great answer

Kyle Petran
Kyle Petran
5,017 Points

Eswar Ambati I fear my answer may be too late for you to find useful; however, I'll clarify for any future readers. Essentially the index is getting incremented, but that doesn't mean the list moves when the index goes up. So although inventory[0] was "apple", once that element was deleted inventory[0] now becomes "orange", but it skips over orange because it has incremented to inventory[1]

really make sense. Thanks