In one of the previous articles we learned how to remove elements from a list. In this article we’ll be talking about one more method that we can use to remove, and at the same time return, an element from a list, the pop method.
Here’s the video version of this article:
We use the pop(i) method to return the i-th element and also remove it:
>>> names = ['Steve', 'Sam', 'Jenny', 'Emma', 'Bernard', 'Alice']
>>> names.pop(-2) # last but one
'Bernard'
>>> names
['Steve', 'Sam', 'Jenny', 'Emma', 'Alice']
An out of range error is raised if the index is out of range:
>>> names.pop(8)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
If we use the pop method without any argument, the last element is returned and removed:
>>> last_person = names.pop()
>>> last_person
'Alice'
>>> names
['Steve', 'Sam', 'Jenny', 'Emma']
It’s easy to use a list as a stack. A stack is a special LIFO data structure. LIFO stands for Last In First Out, because it’s how stacks work. Imagine a stack of plates. If you add a new plate, you put it on top. If you need to take a plate from the stack, you take the one on top. That’s how stacks work.
In computer science we distinguish two methods used with stacks: push to add an element to the end (or top) of the stack, and pop to remove the last element. In Python we can use two methods, append, which is the equivalent of push, and pop to simulate this behavior. The append method adds the element to the end of the list, the pop method pops the last element. Here’s an example:
>>> numbers = [4, 2, 6, 7]
>>> numbers.append(20)
>>> numbers
[4, 2, 6, 7, 20]
>>> numbers.pop()
20
>>> numbers
[4, 2, 6, 7]