Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python remove element from list while looping

# Remove elements from a list while iterating
# What not to do
a = [1, 2, 2, 3, 4]
def even(x):    # helper function
    return x % 2 == 0
for i in a:
    if even(i):
        a.remove(i)     # never loop over a list and remove elements at the same time
a    #[1, 2, 3]     <= 2 is still here. 
# Problem: removed an element while looping over it, 
# so all elements after the removed element are shifted one place to the left, so we skip 1 iteration. 
# the right way is to loop over a copy of the list

# Approach 1: loop over a copy of the list
a = [1, 2, 2, 3, 4]
for i in a[:]:    # loop over a copy of the list
    if even(i):
        a.remove(i)
a   #[1, 3]

# Approach 2: use list comprehension to create a new list
a = [x for x in a if not even(x)]    # [1, 3]
# Faster way, assign in slice of a, so modify in place
a[:] = [x for x in a if not even(x)]    # [1, 3]

# Approach 3: use filter
from itertools import filterfalse
a[:] = filterfalse(even, a)    # [1, 3]
 
PREVIOUS NEXT
Tagged: #python #remove #element #list #looping
ADD COMMENT
Topic
Name
9+2 =