Python List pop() Method



The Python List pop() method removes and returns the last object from the list, by default. However, the method also accepts an optional index argument and the element at the index is removed from the list.

The difference between this method and remove() method is that the pop() method removes the object with the help of indexing technique while the remove() method traverses the list to find the first occurrence of an object.

Syntax

Following is the syntax for the Python List pop() method −

list.pop(obj = list[-1])

Parameters

  • obj − This is an optional parameter, index of the object to be removed from the list.

Return Value

This method returns the removed object from the list.

Example

The following example shows the usage of the Python List pop() method. In here, we are not passing any argument to the method.

aList = [123, 'xyz', 'zara', 'abc']
print("Popped Element : ", aList.pop())
print("Updated List:")
print(aList)

When we run above program, it produces following result −

Popped Element :  abc
Updated List:
[123, 'xyz', 'zara']

Example

But if we pass an index argument to the method, the return value will be the object removed at the given index.

aList = ['abc', 'def', 'ghi', 'jkl']
print("Popped Element : ", aList.pop(2))
print("Updated List:")
print(aList)

If we compile and run the program above, the output is displayed as follows −

Popped Element :  ghi
Updated List:
['abc', 'def', 'jkl']

Example

As we know, negative indexing is allowed in Python and it is done from right to left. So, when we pass a negative index as an argument to the method, the element present at the index is removed.

aList = [123, 456, 789, 876]
print("Popped Element : ", aList.pop(-1))
print("Updated List:")
print(aList)

On executing the program above, the output is as follows −

Popped Element :  876
Updated List:
[123, 456, 789]

Example

However, if the index passed to the method is greater than the length of the List, an IndexError is raised.

aList = [1, 2, 3, 4]
print("Popped Element : ", aList.pop(5))
print("Updated List:")
print(aList)

Let us compile and run the given program, to produce the following result −

Traceback (most recent call last):
  File "main.py", line 2, in 
    print("Popped Element : ", aList.pop(5))
IndexError: pop index out of range
python_lists.htm
Advertisements