Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between del, remove, and pop on lists

Tags:

python

list

Is there any difference between these three methods to remove an element from a list?

>>> 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]
like image 877
sachin irukula Avatar asked Jul 17 '12 10:07

sachin irukula


People also ask

What is the difference between remove Del and pop?

In python del is a keyword and remove(), pop() are in-built methods. The purpose of these three are same but the behavior is different remove() method delete values or object from the list using value and del and pop() deletes values or object from the list using an index.

What is difference between Del and pop () in list?

The pop() function is used to return the removed element from the list. The del() function is used to delete an element at a specified index number in the list.


3 Answers

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
like image 164
Martijn Pieters Avatar answered Oct 12 '22 11:10

Martijn Pieters


Use del to remove an element by index, pop() to remove it by index if you need the returned value, and remove() to delete an element by value. The last requires searching the list, and raises ValueError if no such value occurs in the list.

When deleting index i from a list of n elements, the computational complexities of these methods are

del     O(n - i)
pop     O(n - i)
remove  O(n)
like image 260
Sven Marnach Avatar answered Oct 12 '22 13:10

Sven Marnach


Since no-one else has mentioned it, note that del (unlike pop) allows the removal of a range of indexes because of list slicing:

>>> lst = [3, 2, 2, 1]
>>> del lst[1:]
>>> lst
[3]

This also allows avoidance of an IndexError if the index is not in the list:

>>> lst = [3, 2, 2, 1]
>>> del lst[10:]
>>> lst
[3, 2, 2, 1]
like image 121
Chris_Rands Avatar answered Oct 12 '22 12:10

Chris_Rands