Skip to main content

How to Use the Python pop() Method

Learn how to use Python's pop() method to remove elements from lists and dictionaries, including how to remove items while iterating. Learn to avoid common errors like IndexError and KeyError.
Jul 31, 2024  · 9 min read

The pop() method is an important function in Python that is used in data manipulation to remove and return a specified element from a list or dictionary. Python programmers prefer the pop() method because it is an especially simple way to modify data structures like lists and dictionaries.

Before going into more detail, I highly recommend taking DataCamp’s Introduction to Python course to learn the basics of the Python language. The Python Cheat Sheet for Beginners will also help you reference and understand Python's syntax and different functions.

Quick Answer: How to Use the pop() Method in Python

The pop() method is used in lists and dictionaries to remove specific items and return the value. I will show a quick example for both. The first example shows how to remove an item from a list using the pop() method. The following code prints 5.

# Create a list
my_list = [1, 2, 3, 4, 5]

# Removes and returns the last element of the list
last_element = my_list.pop()
print(last_element)

The next example below shows how to use the pop() method to remove a specific key from a dictionary. The following code prints 3.

# Create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Removes and returns the value associated with the key 'b'
value = my_dict.pop('c')
print(value)

Using pop() with Lists

The pop() method is used with lists to remove and return the specified element from that list. The syntax for the pop() method with lists is shown below.

list.pop([index])

When using the pop() method with lists, know that it can take an optional parameter to specify the index to remove. If no parameter is provided, the pop() method removes and returns the last element from the list.

If, instead, you choose to specify the index explicitly, be aware that if you do so incorrectly, it will raise an IndexError if the specified index is out of range. Let us look at the different use cases of the pop() method with the lists below.

Using pop() to remove element by index

You can also use a positive or negative index as an argument in the pop() method to specify the element to remove from the list. In Python, positive indices start from 0 at the beginning of the list. Negative indices begin from -1 at the end of the list.

The following examples show these three methods for removing elements from a list. In each case, the code output will print 5.

# Create a list
my_list = [1, 2, 3, 4, 5]

# Removes and returns the last element of the list
last_element = my_list.pop()
print(last_element)
# Create a list
my_list = [1, 2, 3, 4, 5]

# Remove specific element using negative index
removed_element = my_list.pop(-1) 
print(removed_element)  
# Create  a list
my_list = [1, 2, 3, 4, 5]

# Remove specific element using negative index
removed_element = my_list.pop(4) 
print(removed_element) 

Using pop() to remove items from a list while iterating

You can use the pop() method in a loop to iterate through the list and remove the last item each time until the list is empty. The example below shows how to use the pop() method in loops. The code below will print List is now empty.

# Create a list
my_list = [1, 2, 3, 4, 5]

# Create a function to remove items from the list
while my_list:
    element = my_list.pop()
    print(f"Removed element: {element}")
print("List is now empty:", my_list)

This technique can be helpful in several scenarios. Imagine, for example, you have a list of tasks to handle one by one. By using pop(), you can remove each task as it's completed, keeping your list focused on what's left. 

Using pop() with nested lists

You can use the pop() method to remove elements from nested lists. This method will remove and return the specified list within the nested list. The following code will print [7, 8, 9].

# Define a nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Pop an element from the outer list
removed_list = nested_list.pop()
print(removed_list)

If you want to remove a specific element from the inner list, you will first specify the list index in the nested list. The code below prints 9, which is the last element of the list at the second index.

# Define a nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Pop an element from an inner list
removed_element = nested_list[2].pop()
print(removed_element)

Handling pop() index out of range

When you try to remove an element from a list with an index out of the range of the specific list, it will raise an IndexError. To avoid this error, it is important first to check the list's length and then provide the appropriate index. You can also use the try-except block to catch the error. The code below will print Index out of range for both cases.

# Create a list
my_list = [1, 2, 3]

# Check length before popping
index = 4

# Ensure the index is within the valid range of the list
if 0 <= index < len(my_list):
    # Removes and returns the element at the specified index
    element = my_list.pop(index)  
    print(f"Popped element: {element}")
else:
    print("Index out of range")
# Create a list
my_list = [1, 2, 3]

# Using try-except block to handle out-of-range index
try:
    # Attempt to remove and return the element at index 5
    element = my_list.pop(5)
except IndexError:
    # Catches the IndexError if the index is out of range
    print("Index out of range")

Using pop() with Dictionaries

The pop() method is used with dictionaries to remove a specified key and return its value. The syntax for the pop() method with dictionaries is shown below.

dict.pop(key[, default])

We can see that the pop() method, when used with a dictionary, requires a key as a parameter. The pop() method returns the value associated with the specified key and removes the key-value pair from the dictionary. 

You can also provide an optional default value to return if the key is not found. If the specified key is not found and no default value is provided, a KeyError is raised. If a default value is provided, it returns that default value instead.

Python dictionary default value

When using the pop() method with dictionaries, you can provide the default value to return if the key value is not found. This method is usually used to prevent the KeyError. The code below prints Not Found since the key d is not in the collection.

# Create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Remove a specific key and provide default value
value = my_dict.pop('d', 'Not Found')

# Prints the returned value
print(value)

Using pop() method with nested dictionaries

Like in lists, you can use the pop() method to remove elements in nested dictionaries. Nested dictionaries are dictionaries within dictionaries. The following code will print {'x': 7, 'y': 8, 'z': 9}.

# Define a nested dictionary
nested_dict = {
    'a': {'x': 1, 'y': 2, 'z': 3},
    'b': {'x': 4, 'y': 5, 'z': 6},
    'c': {'x': 7, 'y': 8, 'z': 9}
}

# Pop a key-value pair from the outer dictionary
removed_dict = nested_dict.pop('c')
print(removed_dict)

You can also remove an inner value from a specific dictionary in nested dictionaries by specifying its key value. The code below prints 2.

# Define a nested dictionary
nested_dict = {
    'a': {'x': 1, 'y': 2, 'z': 3},
    'b': {'x': 4, 'y': 5, 'z': 6},
    'c': {'x': 7, 'y': 8, 'z': 9}
}

# Pop a key-value pair from an inner dictionary
popped_inner_value = nested_dict['a'].pop('y')
print(popped_inner_value)

Handling python dictionary KeyError

Another common approach to handle the KeyError more gracefully is to use a try-except block to catch the error. The following example demonstrates how to use the try-except technique with the pop() method.

# Create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Create the try-except block to catch the error
try:
    value = my_dict.pop('d')
except KeyError:
    print("Key not found")

You can also use the in keyword to check if a specific key exists in a dictionary before removing it. The code below uses this method and returns Key not found.

# Create a dictionary
my_dict = {'a': 1, 'b': 2}

# Check key existence before popping
key = 'c'
if key in my_dict:
    value = my_dict.pop(key)
    print(f"Popped value: {value}")
else:
    print("Key not found.")

Performance Considerations

In this section, we will take a look at the performance implications of using the pop() method with lists and dictionaries.

List operations

The time complexity of the pop() operations in lists depends on the index of the element being removed. When you use the pop() method without an argument or with -1 as the index to remove the last element, it operates in O(1) time because it only removes the last element in the list without changing the other elements.

When we use the pop() method to remove the first or any other element, it works in O(n) time because it involves removing an element and shifting the other elements to a new index order. Check out our Analyzing Complexity of Code through Python tutorial to learn more about time complexity in Python.

Dictionary operations

The pop() method in dictionaries is highly efficient due to the implementation of the underlying hash table. In this scenario, the pop() method with dictionaries is generally an O(1) operation.

This time complexity is due to the dictionary storing the keys in a hash table and requires some time for insertions, deletions, and lookups. Also, note that you must always specify the key to be removed from a dictionary when using the pop() method. Check out our A Guide to Python Hashmaps tutorial to learn more hash tables.

Alternatives to Python’s pop() Method

Although the pop() method is effective in removing elements from lists and dictionaries, there are some alternatives.

Using the del keyword

The del keyword is used to remove an item from a list by specifying the index of the element. The del keyword can also be used to remove specified key-value pairs from dictionaries.  You should note that using the del keyword does not return the removed element, unlike using the pop() method. 

The examples below show how to use the del keyword to remove elements from a list and dictionary. After removing the element at the second index, the following code prints a new list [1, 2, 4, 5].

# Initialize a list with integers from 1 to 5
my_list = [1, 2, 3, 4, 5]

# Remove item at index 2
del my_list[2]
print(my_list)

The following code will print {'a': 1, 'c': 3}.

# Create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Remove the key 'b' and its associated value from the dictionary
del my_dict['b']
print(my_dict)

Using the remove() method

The remove() method applies only to a list when you want to remove an element by its exact value rather than index. This method removes the specified element's first occurrence if it appears more than once in the list. The code below prints [1, 3, 4, 5].

# Initialize a list with integers from 1 to 5
my_list = [1, 2, 3, 4, 5]

# Remove the element with the value 2 from the list
my_list.remove(2)
print(my_list)

Conclusion

The pop() method is an especially simple and versatile feature in Python used to remove elements from lists and dictionaries, which has all kinds of practical applications in programming. This pop() method is especially important when handling lists and dictionaries since it returns the removed element, which is often the exact behavior you are looking for.

As a data analyst, I recommend checking DataCamp’s Python Fundamentals and Python Programming skill tracks to improve your Python skills for data analysis. I also encourage you to check our Data Analyst with Python career track to help you keep building practical, job-relevant skills.


Photo of Allan Ouko
Author
Allan Ouko
LinkedIn
I create articles that simplify data science and analytics, making them easy to understand and accessible.

Frequently Asked Questions

What does the pop() method do?

The pop() method removes and returns n element from lists or dictionaries.

What is IndexError in the pop() method?

An IndexError occurs when you try to remove an element with an index out of range.

What are the alternatives to the pop() method?

The remove() method and del keyword are the alternative methods for removing elements from lists or dictionaries.

What is the difference between the pop() and remove() methods?

The pop() method removes and returns the specified element by index from a list or dictionary. The remove() method removes an element from a list or dictionary by its value and does not return the value.

What is the time complexity of the pop() method?

The pop() method default time complexity is O(1), which is constant and efficient.

Can the pop() method be applied to data structures other than lists and dictionaries in Python?

Yes, the pop() method can also be applied to sets and bytearrays in Python. For sets, set.pop() removes and returns an arbitrary element, as sets are unordered. For bytearrays, bytearray.pop(index) removes and returns the element at the specified index, similar to how it works with lists.

Topics

Learn Python with DataCamp

track

Python Programming

19hrs hr
Level-up your programming skills. Learn how to optimize code, write functions and tests, and use best-practice software engineering techniques.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

How to Split Lists in Python: Basic Examples and Advanced Methods

Learn how to split Python lists with techniques like slicing, list comprehensions, and itertools. Discover when to use each method for optimal data handling.
Allan Ouko's photo

Allan Ouko

11 min

tutorial

Python List Functions & Methods Tutorial and Examples

Learn about Python List functions and methods. Follow code examples for list() and other Python functions and methods now!
Abid Ali Awan's photo

Abid Ali Awan

7 min

tutorial

Python Count Tutorial

Learn how to use the counter tool with an interactive example.
DataCamp Team's photo

DataCamp Team

3 min

tutorial

How to Sort a Dictionary by Value in Python

Learn efficient methods to sort a dictionary by values in Python. Discover ascending and descending order sorting and bonus tips for key sorting.
Neetika Khandelwal's photo

Neetika Khandelwal

5 min

tutorial

18 Most Common Python List Questions

Discover how to create a list in Python, select list elements, the difference between append() and extend(), why to use NumPy and much more.
Karlijn Willems's photo

Karlijn Willems

34 min

tutorial

Python Tutorial for Beginners

Get a step-by-step guide on how to install Python and use it for basic data science functions.
Matthew Przybyla's photo

Matthew Przybyla

12 min

See MoreSee More