You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output. You can also use negative index values.
The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.
In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.
There are two options to remove an element by its index in list. Using del statement, and using pop() method. The del statement needs index of the element to remove. The pop() method of built-in list class requires index as argument.
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.
You probably want pop
:
a = ['a', 'b', 'c', 'd']
a.pop(1)
# now a is ['a', 'c', 'd']
By default, pop
without any arguments removes the last item:
a = ['a', 'b', 'c', 'd']
a.pop()
# now a is ['a', 'b', 'c']
Like others mentioned pop and del are the efficient ways to remove an item of given index. Yet just for the sake of completion (since the same thing can be done via many ways in Python):
Using slices (this does not do in place removal of item from original list):
(Also this will be the least efficient method when working with Python list, but this could be useful (but not efficient, I reiterate) when working with user defined objects that do not support pop, yet do define a __getitem__
):
>>> a = [1, 2, 3, 4, 5, 6]
>>> index = 3 # Only positive index
>>> a = a[:index] + a[index+1 :]
# a is now [1, 2, 3, 5, 6]
Note: Please note that this method does not modify the list in place like pop
and del
. It instead makes two copies of lists (one from the start until the index but without it (a[:index]
) and one after the index till the last element (a[index+1:]
)) and creates a new list object by adding both. This is then reassigned to the list variable (a
). The old list object is hence dereferenced and hence garbage collected (provided the original list object is not referenced by any variable other than a).
This makes this method very inefficient and it can also produce undesirable side effects (especially when other variables point to the original list object which remains un-modified).
Thanks to @MarkDickinson for pointing this out ...
This Stack Overflow answer explains the concept of slicing.
Also note that this works only with positive indices.
While using with objects, the __getitem__
method must have been defined and more importantly the __add__
method must have been defined to return an object containing items from both the operands.
In essence, this works with any object whose class definition is like:
class foo(object):
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return foo(self.items[index])
def __add__(self, right):
return foo( self.items + right.items )
This works with list
which defines __getitem__
and __add__
methods.
Comparison of the three ways in terms of efficiency:
Assume the following is predefined:
a = range(10)
index = 3
The del object[index]
method:
By far the most efficient method. It works will all objects that define a __del__
method.
The disassembly is as follows:
Code:
def del_method():
global a
global index
del a[index]
Disassembly:
10 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 DELETE_SUBSCR # This is the line that deletes the item
7 LOAD_CONST 0 (None)
10 RETURN_VALUE
None
pop
method:
It is less efficient than the del method and is used when you need to get the deleted item.
Code:
def pop_method():
global a
global index
a.pop(index)
Disassembly:
17 0 LOAD_GLOBAL 0 (a)
3 LOAD_ATTR 1 (pop)
6 LOAD_GLOBAL 2 (index)
9 CALL_FUNCTION 1
12 POP_TOP
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
The slice and add method.
The least efficient.
Code:
def slice_method():
global a
global index
a = a[:index] + a[index+1:]
Disassembly:
24 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 SLICE+2
7 LOAD_GLOBAL 0 (a)
10 LOAD_GLOBAL 1 (index)
13 LOAD_CONST 1 (1)
16 BINARY_ADD
17 SLICE+1
18 BINARY_ADD
19 STORE_GLOBAL 0 (a)
22 LOAD_CONST 0 (None)
25 RETURN_VALUE
None
Note: In all three disassembles ignore the last two lines which basically are return None
. Also the first two lines are loading the global values a
and index
.
pop
is also useful to remove and keep an item from a list. Where del
actually trashes the item.
>>> x = [1, 2, 3, 4]
>>> p = x.pop(1)
>>> p
2
If you want to remove elements at specific positions in a list, like the 2nd, 3rd and 7th elements, you can't use
del my_list[2]
del my_list[3]
del my_list[7]
Since after you delete the second element, the third element you delete actually is the fourth element in the original list. You can filter the 2nd, 3rd and 7th elements in the original list and get a new list, like below:
new_list = [j for i, j in enumerate(my_list) if i not in [2, 3, 7]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With