Skip to content
Home » The pop Method in Python

The pop Method in Python

Spread the love

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.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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]

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply