Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

remove item from list while looping

l = ["a", "b", "c", "d", "e"]
for item in l[:]:
     if item == "b":
        l.remove(item)
 
print(l)
#the main trick of this problem is the traditional for loop will not work...it will give an "out of range" error saying
#this is because you are changing the list that you are for looping
#the traditional for loop will not work because you are changing the list it is iterating 
Comment

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]
Comment

PREVIOUS NEXT
Code Example
Python :: How to set "Unnamed: 0" column as the index in a DataFrame 
Python :: download youtube video in python 
Python :: replace nan in pandas 
Python :: quadratic formula python 
Python :: difference between two dates in days python 
Python :: random chiece python 
Python :: message box for python 
Python :: scipy stats arithmetic mean 
Python :: python zip listas diferente tamaño 
Python :: individuare stella polare con piccolo carro 
Python :: fruit shop using list in python 
Python :: How to get key value list from selection fields in Odoo 10 
Python :: import pandas 
Python :: how to remove stopwords from a string in python 
Python :: Python create a digital clock 
Python :: Join a list of items with different types as string in Python 
Python :: make python file executable linux 
Python :: absolut beginners projects in python with tutorial 
Python :: python immutable default parameters 
Python :: iterating over 2d array python 
Python :: convert string array to integer python 
Python :: sudo not include packages in python 
Python :: python last element in list 
Python :: numpy array heaviside float values to 0 or 1 
Python :: list python shuffling 
Python :: python requests force ipv4 
Python :: bs4 find element by id 
Python :: yapf ignore line 
Python :: get all paragraph tags beautifulsoup 
Python :: remove stopwords from list of strings python 
ADD CONTENT
Topic
Content
Source link
Name
6+2 =