gotchapythonCriticalCanonical
Difference between del, remove, and pop on lists in Python
Viewed 0 times
delandbetweenlistsremovedifferencepoppython
Problem
Is there any difference between these three methods to remove an element from a list in Python?
a = [1, 2, 3]
a.remove(2)
a # [1, 3]
a = [1, 2, 3]
del a[1]
a # [1, 3]
a = [1, 2, 3]
a.pop(1) # 2
a # [1, 3]
Solution
The effects of the three different methods to remove an element from a list:
and
Their error modes are different too:
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 "", line 1, in
ValueError: list.remove(x): x not in list
>>> del a[7]
Traceback (most recent call last):
File "", line 1, in
IndexError: list assignment index out of range
>>> a.pop(7)
Traceback (most recent call last):
File "", line 1, in
IndexError: pop index out of rangeCode Snippets
>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]>>> a = [9, 8, 7, 6]
>>> del a[1]
>>> a
[9, 7, 6]>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]>>> 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 rangeContext
Stack Overflow Q#11520492, score: 1695
Revisions (0)
No revisions yet.