How to Use the Python pop() Function?

In this tutorial, I will explain how to use the Python pop() function. While building the to-do list application in Python, I needed to implement the functionality of removing a task when it was completed. So, I used the Python pop() method to remove the task dynamically. We will explore various use cases, and I will share some examples and screenshots of executed example code.

The pop() function is a built-in method in Python that allows you to remove and return an element from a list or dictionary. This function is useful when manipulating data by dynamically removing items from collections.

Syntax of the pop() Function in Python

For a list:

list.pop([index])

For a dictionary:

dictionary.pop(key[, default])

Parameters

  • index: The element you want to remove from the list. If not provided, the last element is removed.
  • key: The key of the element you want to remove from the dictionary.
  • default: A value to return if the specified key does not exist.

Read How to Convert a Dictionary to a List in Python

Use pop() with Python Lists

Let us see how to use pop() with Python lists.

1. Remove the Last Element

By default, the pop() method removes the last element from a list. Let’s consider an example where we have a list of popular cities in the USA.

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
last_city = cities.pop()
print("Removed City:", last_city)
print("Updated List:", cities)

Output:

Removed City: Phoenix
Updated List: ['New York', 'Los Angeles', 'Chicago', 'Houston']

I have executed the above example code and added the screenshot below.

the Python pop() Function

Check out Should I Learn Java or Python

2. Remove an Element by Index

You can also specify the index of the element you want to remove. For instance, if we want to remove “Chicago” from our list:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
removed_city = cities.pop(2)
print("Removed City:", removed_city)
print("Updated List:", cities)

Output:

Removed City: Chicago
Updated List: ['New York', 'Los Angeles', 'Houston', 'Phoenix']

I have executed the above example code and added the screenshot below.

Use the Python pop() Function

Read PyCharm vs. VS Code for Python

Use pop() with Python Dictionaries

Let us see how to use pop() with Python dictionaries.

1. Remove an Element by Key

The pop() method can also be used with dictionaries to remove a key-value pair. Let’s say we have a dictionary of state capitals:

state_capitals = {
    "New York": "Albany",
    "California": "Sacramento",
    "Illinois": "Springfield",
    "Texas": "Austin",
    "Arizona": "Phoenix"
}
removed_capital = state_capitals.pop("Illinois")
print("Removed Capital:", removed_capital)
print("Updated Dictionary:", state_capitals)

Output:

Removed Capital: Springfield
Updated Dictionary: {'New York': 'Albany', 'California': 'Sacramento', 'Texas': 'Austin', 'Arizona': 'Phoenix'}

I have executed the above example code and added the screenshot below.

How to Use the Python pop() Function

Read How to Get the Length of a Dictionary in Python

2. Provide a Default Value

If you try to remove a key that does not exist, the pop() method will raise a KeyError. To avoid this, you can provide a default value:

removed_capital = state_capitals.pop("Florida", "Not Found")
print("Removed Capital:", removed_capital)

Output:

Removed Capital: Not Found

Check out How to Reshape an Array in Python Using the NumPy Library

Practical Use Cases

Manage a To-Do List

Imagine you are building a to-do list application. You can use the pop() method to remove and return the last task when a user marks it as completed.

tasks = ["Buy groceries", "Call Mike", "Finish report", "Book flight"]
completed_task = tasks.pop()
print("Completed Task:", completed_task)
print("Remaining Tasks:", tasks)

Output:

Completed Task: Book flight
Remaining Tasks: ['Buy groceries', 'Call Mike', 'Finish report']

Check out Find Random Number Between Two Values in Numpy

Handle User Sessions

In a web application, you might need to manage user sessions. You can use a dictionary to store session data and the pop() method to remove a session when a user logs out.

user_sessions = {
    "user1": "session1",
    "user2": "session2",
    "user3": "session3"
}
logged_out_session = user_sessions.pop("user2")
print("Logged Out Session:", logged_out_session)
print("Active Sessions:", user_sessions)

Output:

Logged Out Session: session2
Active Sessions: {'user1': 'session1', 'user3': 'session3'}

Read How to Convert Tensor to Numpy in TensorFlow

Common Issues

Index Out of Range

When using pop() with lists, you must ensure that the index you provide is within the range of the list. Otherwise, you will encounter an IndexError.

cities = ["New York", "Los Angeles", "Chicago"]
# This will raise an IndexError
removed_city = cities.pop(5)

KeyError in Dictionaries

Similarly, when using pop() with dictionaries, trying to remove a key that does not exist without providing a default value will raise a KeyError.

state_capitals = {
    "New York": "Albany",
    "California": "Sacramento"
}
# This will raise a KeyError
removed_capital = state_capitals.pop("Texas")

Check out NumPy array to a string in Python

Conclusion

In this tutorial, I helped you to learn how to use the Python pop() function. I explained the syntax of the pop() function in Python, parameters, using the pop() function with Python lists to remove the last element and remove by index, using the pop() function with Python dictionaries remove an element by key and to provide a default value. I discussed some use cases and common issues.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.