How to remove list elements in a for loop in Python? [duplicate]

Posted on

Solving problem is about exposing yourself to as many situations as possible like How to remove list elements in a for loop in Python? [duplicate] and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about How to remove list elements in a for loop in Python? [duplicate], which can be followed any time. Take easy to follow this discuss.

How to remove list elements in a for loop in Python? [duplicate]

I have a list

a = ["a", "b", "c", "d", "e"]

I want to remove elements in this list in a for loop like below:

for item in a:
    print item

But it doesn’t work. What can I do?

Asked By: alwbtc


Answer #1:

You are not permitted to remove elements from the list while iterating over it using a for loop.

The best way to rewrite the code depends on what it is you’re trying to do.

For example, your code is equivalent to:

for item in a:
  print item
a[:] = []

Alternatively, you could use a while loop:

while a:
  print a.pop(0)

I’m trying to remove items if they match a condition. Then I go to next item.

You could copy every element that doesn’t match the condition into a second list:

result = []
for item in a:
  if condition is False:
a = result

Alternatively, you could use filter or a list comprehension and assign the result back to a:

a = filter(lambda item:... , a)


a = [item for item in a if ...]

where ... stands for the condition that you need to check.

Answered By: NPE

Answer #2:

Iterate through a copy of the list:

>>> a = ["a", "b", "c", "d", "e"]
>>> for item in a[:]:
    print item
    if item == "b":
>>> print a
['a', 'c', 'd', 'e']
Answered By: Alex L

Answer #3:

As other answers have said, the best way to do this involves making a new list – either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable. The difference between these depends on your use case, since they affect other variables for the original list differently (or, rather, the first affects them, the second doesn’t).

If a copy isn’t an option for some reason, you do have one other option that relies on an understanding of why modifying a list you’re iterating breaks. List iteration works by keeping track of an index, incrementing it each time around the loop until it falls off the end of the list. So, if you remove at (or before) the current index, everything from that point until the end shifts one spot to the left. But the iterator doesn’t know about this, and effectively skips the next element since it is now at the current index rather than the next one. However, removing things that are after the current index doesn’t affect things.

This implies that if you iterate the list back to front, if you remove an item at the current index, everything to it’s right shifts left – but that doesn’t matter, since you’ve already dealt with all the elements to the right of the current position, and you’re moving left – the next element to the left is unaffected by the change, and so the iterator gives you the element you expect.


>>> a = list(range(5))
>>> for b in reversed(a):
    if b == 3:
>>> a
[0, 1, 2, 4]

However, making a copy is usually better in terms of making your code easy to read. I only mention this possibility for sake of completeness.

Answered By: lvc

Answer #4:

import copy
a = ["a", "b", "c", "d", "e"]
b = copy.copy(a)
for item in a:
    print item
a = copy.copy(b)

Works: to avoid changing the list you are iterating on, you make a copy of a, iterate over it and remove the items from b. Then you copy b (the altered copy) back to a.

Answered By: user3848191

Answer #5:

How about creating a new list and adding elements you want to that new list. You cannot remove elements while iterating through a list

Answered By: cobie

Answer #6:

Probably a bit late to answer this but I just found this thread and I had created my own code for it previously…

    list = [1,2,3,4,5]
    deleteList = []
    processNo = 0
    for item in list:
        if condition:
            print item
            deleteList.insert(0, processNo)
        processNo += 1
    if len(deleteList) > 0:
        for item in deleteList:
            del list[item]

It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the “insert” inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.

Answered By: Todd Robards
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.