To remove an item from a list, we have two options. One is using del mylist[i]
where i is the index. Other is call mylist.remove(i)
method where i
is item in the list.
Generally, you would remove item from list if a certain condition is satisfied. Assuming that we want to delete even numbers from mylist
, the iteration with index results in error
mylist=[5,3,7,8,20,15,2,6,10,1]
l=len(mylist)
for i in range(l):
if (mylist[i]%2==0):
del mylist[i]
IndexError: list index out of range
This is because list object is dynamically resized as items get deleted. Hence this method for removing item while iterating list doesn't work. A workaround for this could be to employ a decrementing loop. In this example, list size is 10, hence decrement index from 9 to 0
mylist=[5,3,7,8,20,15,2,6,10,1]
for i in range(len(mylist)-1, -1, -1):
if mylist[i]%2==0:
del mylist[i]
print (mylist)
[5, 3, 7, 15, 1]
Calling remove()
method of List object also gives incorrect result
mylist=[5,3,7,8,20,15,2,6,10,1]
for i in mylist:
if (i%2==0):
mylist.remove(i)
print (mylist)
[5, 3, 7, 20, 15, 6, 1]
We can see that even numbers 20 and 6 are not deleted. This is because when i becomes 8, it is removed and items on right move one place to left and 20 becomes current item before next iteration. Similarly after 2 is removed, 6 becomes current item and escapes condition for removal.
The answer to this strange situation is using list comprehension
mylist=[5,3,7,8,20,15,2,6,10,1]
mylist=[i for i in mylist if i%2!=0]
print(mylist)
[5, 3, 7, 15, 1]
We can also use built-in filter()
function. First argument is a function itself which is applied to each item in list and returns an iterator containing those items of list for which argument function evaluates to true.
mylist=[5,3,7,8,20,15,2,6,10,1]
mylist=list(filter(lambda x:x%2!=0, mylist))
print (mylist)
[5, 3, 7, 15, 1]
Another way is to use filterfalse()
function defined in itertools
module.
from itertools import filterfalse
mylist=[5,3,7,8,20,15,2,6,10,1]
def iseven(i):
if i%2==0:
return i
mylist=list(filterfalse(iseven, mylist))
print (mylist)
[5, 3, 7, 15, 1]
- Remove duplicate items from list in Python
- How to sort dictionary by value in Python?
- Convert User Input to a Number
- Convert String to Datetime in Python
- How to count the occurrences of a list item?
- How to flatten list in Python?
- How to merge dictionaries in Python?
- Compare strings in Python
- Convert file data to list