List pop() method Python

The list pop() method is used to remove an element at any given position,note the position counting starts from 0.The pop() method in removing the element returns that element.

>>> ls=['1', 'Hap', ('Too',) , 1 , 34 ]
>>> ls.pop( 2 ) #Element counting starts from 0
('Too',) #this element is removed
>>> ls
['1', 'Hap', 1, 34]
>>> ls.pop(-2)

The difference between remove() method and pop() method is that to use remove() method we must know the specific element to be removed while with pop() knowing just the position is fine.

Link : List remove() method

Point to note

If the position passed does not contain any elements then an error message is returned.

>>> ls=['1', 'Hap', 1, 34]
>>> ls.pop( 10 )
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
IndexError: pop index out of range

We get the error message ‘pop index out of range’ index refers to the position passed.

If we passed no index value or argument to pop() method then the last element is remove from the list object.

>>> ls=['1', 'Hap', 1, 34]
>>> ls.pop()
>>> ls.pop()
>>> ls
['1', 'Hap', 1 ]

Leave a Reply

Your email address will not be published. Required fields are marked *