Difference between del, remove, and pop on lists
The effects of the three different methods to remove an element from a list:
remove
removes the first matching value, not a specific index:
>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]
del
removes the item at a specific index:
>>> a = [9, 8, 7, 6]
>>> del a[1]
>>> a
[9, 7, 6]
and pop
removes the item at a specific index and returns it.
>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]
Their error modes are different too:
>>> a = [4, 5, 6]
>>> a.remove(7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> del a[7]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a.pop(7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
How to remove items from a list while iterating?
You can use a list comprehension to create a new list containing only the elements you don't want to remove:
somelist = [x for x in somelist if not determine(x)]
Or, by assigning to the slice somelist[:]
, you can mutate the existing list to contain only the items you want:
somelist[:] = [x for x in somelist if not determine(x)]
This approach could be useful if there are other references to somelist
that need to reflect the changes.
Instead of a comprehension, you could also use itertools
. In Python 2:
from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)
Or in Python 3:
from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)
How to remove items from a list?
Write code in remove() to remove the item in slot pos, shifting the items beyond it to close the gap, and leaving the value None in the last slot.
You can use the pop
method of list
to remove the item and then append None
to the list.
def remove(lst: list, pos: int):
lst.pop(pos)
lst.append(None)
How to remove an element from a list by index
Use del
and specify the index of the element you want to delete:
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Also supports slices:
>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]
Here is the section from the tutorial.
Removing items from a list
You need to use Iterator
and call remove()
on iterator
instead of using for
loop.
How to remove multiple items from a list in just one statement?
In Python, creating a new object e.g. with a list comprehension is often better than modifying an existing one:
item_list = ['item', 5, 'foo', 3.14, True]
item_list = [e for e in item_list if e not in ('item', 5)]
... which is equivalent to:
item_list = ['item', 5, 'foo', 3.14, True]
new_list = []
for e in item_list:
if e not in ('item', 5):
new_list.append(e)
item_list = new_list
In case of a big list of filtered out values (here, ('item', 5)
is a small set of elements), using a set
is faster as the in
operation is O(1) time complexity on average. It's also a good idea to build the iterable you're removing first, so that you're not creating it on every iteration of the list comprehension:
unwanted = {'item', 5}
item_list = [e for e in item_list if e not in unwanted]
A bloom filter is also a good solution if memory is not cheap.
delete elements from list in python and avoid shifting
As you said, when the item is deleted, the list moves. Since the for loop uses the index within the loop, it gets the index wrong and the wrong item gets removed.
A simple way around this, if you don't wish to rewrite a lot of code is to traverse the list backwards
list = [0, 0, 0, 1, 1, 0 ,0, 1, 0]
for elem in reversed(list):
if elem == 0:
list.remove(elem)
print(list)
Remove an item in list and get a new list?
If you want to have a new list without the third element then:
b = a[:2] + a[3:]
If you want a list without value '3':
b = [n for n in a if n != 3]
Remove items from list if it exists
if [items] in list
checks that: a list containing the list of items is an element of the list. That is, you are asking: is [[1, 2, 3]]
a member of the list? Probably not.
What you want to do is iterate over the element of items_to_remove
and do what you did
for item in items_to_remove:
if item in list:
list.remove(item)
Related Topics
Why Integer.Max_Value + 1 == Integer.Min_Value
Calling Static Method from Another Java Class
Mocking Time in Java 8's Java.Time API
Java - How to Create New Entry (Key, Value)
When Does the Main Thread Stop in Java
Jce Cannot Authenticate the Provider Bc in Java Swing Application
How Pause and Then Resume a Thread
Java.Net.Socketexception: Software Caused Connection Abort: Recv Failed
Karate Karate-Config.Js Not a Js Function
Converting String to Date Using Simpledateformat Is Returning Random Date
Read Rsa Private Key of Format Pkcs1 in Java
Rounding Up a Number to Nearest Multiple of 5
Apache Commons Equals/Hashcode Builder
Best Practice for Passing Many Arguments to Method
Find an Array Inside Another Larger Array