List Pop Method in Python

From this tutorial, you will be learning about Python list POP method. You will see how to use it with lists with the help of examples.

Note: The syntax used here is for Python 3. You may modify it to use with other versions of Python.

Python List POP

To Learn Python from Scratch – Read Python Tutorial

List POP Method

The POP() is a built-in method that removes and displays the element either at the end of a list or at the position given by the user. It is a list-only method.

The syntax used is as follows:

List_name.pop(index)

It takes an argument for the index and returns the element that exists at the index.

When it gets called without an argument, the last element goes away by default.

Note: The index of a list always starts with zero and ends with an arbitrary index.

How does the POP method work?

The pop method takes an index value and checks whether the list exists, removes the element at the index and then displays it after the removal.

It does not work when the index is out of bounds or out of range. IndexError gets displayed for out of bound values.

The index can also be zero or have positive or negative values. In case of a -ve input, the elements get accessed in the reverse direction.

The flowchart for the mechanism is as follows:

Python List POP Flowchart

POP Method Examples

Negative Indexes with POP

List = [1, 8, 27, 64, 125, 216]

print("Before POP:", List)

List.pop(-1)

List.pop(-2)

print("After POP:", List)

#Output:

Before POP: [1, 8, 27, 64, 125, 216]
After POP: [1, 8, 27, 125]

Positive Indexes with POP

List = [1, 8, 27, 64, 125, 216]

print("Before POP:", List)

List.pop(2)

List.pop(4)

print("After POP:", List)

#Output:

Before POP: [1, 8, 27, 64, 125, 216]
After POP: [1, 8, 64, 125]

Invalid Indexes with POP

3.1 Example:

List = ["Chair", "Table", "Spoon", "Plates"]

print("Before POP:", List)

List.pop(-5)

print("After POP:", List)

#Output:

Traceback (most recent call last):
File "C:\Python\Python35\listpop.py", line 5, in <module>
List.pop(-5)
IndexError: pop index out of range

3.2 Example:

List = ["Chair", "Table", "Spoon", "Plates"]

print("Before POP:", List)

List.pop(4)

print("After POP:", List)

#Output:

Traceback (most recent call last):
File "C:\Python\Python35\listpop.py", line 5, in <module>
List.pop(4)
IndexError: pop index out of range

Best,

TechBeamers