Python List – pop()

Python list.pop() method deletes the last object from the list, and returns the deleted object.

Pop operation modifies the original list, and reduces the length of the Python List by 1.

Calling pop() on an empty list causes IndexError.

Syntax

The syntax to call pop() method on a list myList is

myList.pop()

Examples

Pop Item from a non-empty List

In the following program, we initialize a list with some elements, and pop an item from the list.

main.py

#initialize list
myList = ['apple', 'banana', 'cherry']

#pop item from list
item = myList.pop()

#print popped item
print(f'popped item is : {item}')

#print list
print(f'resulting list : {myList}')

Output

popped item is : cherry
resulting list : ['apple', 'banana']

Pop Item from an empty List

Now, we shall take an empty list, and try popping an element from this empty list.

main.py

#empty list
myList = []

#pop item from list
item = myList.pop()

#print popped item
print('popped item is :', item)

#print list
print(myList)

Output

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    item = aList.pop()
IndexError: pop from empty list

Since, the list is empty, pop() method raises IndexError.

Conclusion

In this Python Tutorial, we learned how to pop an item from the end of list using list.pop() method.