Friday 15 September 2017

Difference between del, remove and pop on lists in python.


remove removes the first matching value:
>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]
del removes a specific index:
>>> a = [3, 2, 2, 1]
>>> del a[1]
[3, 2, 1]
and pop returns the removed element:
>>> 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

pop : Takes Index & returns Value
remove : Takes value, removes first occurrence and returns nothing
delete : Takes index, removes value at that index and returns nothing

No comments:

Post a Comment