Python Introducing Lists Using Lists Mutability

Why calling remove method on the master list doesn't remove all the elements?

I don't understand this "YOU MUTATE THE LIST WHILE LOOPING OVER IT", list = ['Here', 'There', 'How', 'Wow'] for v in list: list.remove(v) #why it doesn't remove all the elements? as shown in the video? why do we have to make a copy of the list to remove all the elements? Would anyone please tell me what's the concept behind it?

2 Answers

Yang Hu
Yang Hu
7,782 Points

Just checked the other post and had this issue figured out. Basically when your removal iteration starts, the most-left item will be removed, creating a new indexing for the list, which creates problem for the on-going loop order.

Assume this is your original list,

list = ["1", "2", "3", "4", "5"]

and what happens when your loop starts is: list.remove([0]), hence your list become:

list = ["2", "3", "4", "5"]

but then the loop does not stop, it will do: list.remove([1]) to the code above, hence your list become:

list = ["2", "4", "5"]

but then the loop still does not stop, it will do: list.remove([2]) to the code above, hence your list become:

list = ["2", "4"]

then the loop still still does not stop, it will do: list.remove([3]) to the code above, which your list does not have anymore, hence your list stays the same and the loop ends:

list = ["2", "4"]

My first time answering question in the forum, hope it's helpful.

Steven Parker
Steven Parker
176,806 Points

When you modify an iterator by removing items while it is being used to control a loop, it throws off the internal loop mechanisms and causes items to be skipped over. Similarly, if you were to add items instead, it could cause some items to be used twice.

Using a copy of the item as the iterator prevents this issue.

Ceil-Ian Maralit
Ceil-Ian Maralit
Front End Web Development Techdegree Graduate 19,292 Points

Hi Steven Parker,

I totally agree with the both of you. But I'm just a little confused with the copying thing and need a confirmation. :)

It does need to make a copy while looping when mutating at the same time because it resets the whole list again starting with the index 0 and prevents it to skip an item inside that list during the loop. Am I right? Please correct me if I'm wrong. Thank you!

Steven Parker
Steven Parker
176,806 Points

The index might not become 0, but the important thing is that the index might not point to the next item, but instead to one past it. See the step-by-step Yang posted that illustrates what happens.