Home > Back-end >  About removing an item from a list with a for loop
About removing an item from a list with a for loop

Time:05-07

Let's say we try to remove all elements of a list with the following code:

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

Of course this is not "permitted" and will fail. On the other hand we could do:

a = [1, 2, 3, 4]
for i in list(a):
    a.remove(i)

and this would work. So, I have two questions:

  1. Why is the second method working?
  2. Is the second method acceptable and should be used?

Thank you in advance!

CodePudding user response:

The second code works because a new list is created with list(a). You then iterate through the new list and remove items from the original list.

The second code is acceptable in the sense that you are not iterating through the same list you are modifying.

CodePudding user response:

You can get some sense about the process by adding prints to your code:

a = [1, 2, 3, 4]
for i in a:
    print('Deleting: {}'.format(i))
    a.remove(i)
print(a)

In your first sample, the loop starts with deleting 1, and then moving on to the second element in the list. However, since you deleted 1, the next element in terms of the loop is the second element in the list, which is now 3 (2 is the first now) - so the loop deletes 3. And then it wants to delete the third element, but no such element any more.

In the second sample, list(a) actually creates a new instance of a list (with the same elements as a), so what you actually do is to iterate over the elements of this new list, and delete the corresponding elements in original a. Since both lists hold the same elements - all the elements in a are being deleted.

About what your second question about what is accepted - it all depends what you'd like to achieve.

  • Related