Pop in Python: An Introduction to Pop Function with Examples
By Rohit Sharma
Updated on Apr 17, 2025 | 20 min read | 1.5k views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Apr 17, 2025 | 20 min read | 1.5k views
Share:
Table of Contents
Latest Update: Python 3.14 Alpha version released in February 2025. This release brings exciting improvements to the language. Learning Python functions, such as pop(), remains key to writing clean, efficient, and powerful code.
The pop() function in Python is a versatile method used to remove an item from a list and return its value. It's particularly useful when you need to extract an element from a specific position or just need to remove the last element of the list. For example, imagine you’re building a shopping cart system. You can use pop() to remove items from the cart as users decide to checkout or remove products they no longer want.
In this guide, you will learn what the pop() function is, how it works, and how it can help simplify list manipulation and enhance your coding efficiency in 2025.
In Python, pop() is a built-in method used primarily to remove an item from a list or dictionary. It’s a handy tool when you want to get rid of an element and need to access it at the same time.
Whether you're handling lists or dictionaries, pop() allows you to both remove and retrieve an element in a single operation.
Why does it matter?
The pop() method removes and returns an item from a list or dictionary. If no index or key is provided, it removes the last item from the list or dictionary. If you specify an index for a list or a key for a dictionary, it will remove the specified item.
List: Removes and returns an element at the specified index or the last element if no index is given.
Dictionary: Removes and returns the value for the specified key. If the key isn’t found, it can return a default value, making your code more robust.
In coding, data manipulation is essential. Maybe you're building applications that process user input, manage inventories, or update configurations. The pop() function streamlines these tasks by allowing you to efficiently remove and access elements.
For example, imagine you're building a menu-driven application where users select items from a list. As the user chooses options, you can use pop() to remove their choices, ensuring they don’t appear in the list again.
In practical scenarios, pop() is especially useful in data structures like stacks or queues, or for managing tasks such as implementing undo functionality in an app. In these cases, pop() helps manage changes dynamically, whether you're processing tasks or rolling back an action to a previous state.
For instance:
tasks = ['Buy groceries', 'Clean room', 'Pay bills']
completed_task = tasks.pop(0) # Removes 'Buy groceries'
print(f"Completed task: {completed_task}")
print(f"Remaining tasks: {tasks}")
Output:
Completed task: Buy groceries
Remaining tasks: ['Clean room', 'Pay bills']
Here, pop() allows you to retrieve and remove the first task from the list, simplifying task management.
Also Read: OOP vs POP: Difference Between POP and OOP
Let’s break down the syntax for both lists and dictionaries, focusing on how pop() can simplify your code.
1. For Lists:
list.pop([index])
index (optional): The position in the list from which to remove the item. If no index is given, it removes the last item.
Why use pop() over del or remove()?
Example:
numbers = [10, 20, 30, 40]
removed_item = numbers.pop(1) # Removes the item at index 1
print(f"Removed item: {removed_item}")
print(f"Updated list: {numbers}")
Output:
Removed item: 20
Updated list: [10, 30, 40]
2. For Dictionaries:
dict.pop(key[, default])
key: The key to remove.
default (optional): The value returned if the key doesn’t exist.
Why use pop() over alternatives like del?
Example:
user_info = {'name': 'Alice', 'age': 30, 'city': 'New York'}
removed_value = user_info.pop('age')
print(f"Removed value: {removed_value}")
print(f"Updated dictionary: {user_info}")
Output:
Removed value: 30
Updated dictionary: {'name': 'Alice', 'city': 'New York'}
Here, the pop() method is used to remove a key-value pair from the dictionary, returning the value of the removed key.
Understanding its syntax can make your code cleaner and more efficient.
Also Read: Python Cheat Sheet: From Fundamentals to Advanced Concepts for 2025
Now that you are familiar with pop function, let’s understand how to use pop in Python.
The pop() function is a fundamental tool in Python that simplifies the process of modifying lists and dictionaries. It allows you to remove an item from a collection while also returning the item, which makes it ideal for scenarios where you need to manipulate data and keep track of what’s been removed.
Let’s dive deeper into how pop() works, explore real-life examples, and discuss common edge cases to make sure you're using it to its fullest potential.
The pop() method is used to remove and return an item from a list. If you don’t specify an index, it removes the last item. If you do provide an index, it removes the item at that specific position. This flexibility makes pop() particularly useful in tasks like handling dynamic data in lists.
Basic Usage: list.pop() and list.pop(index)
Example 1: Basic pop() without index
numbers = [10, 20, 30, 40]
last_item = numbers.pop() # Removes and returns the last item
print(f"Removed item: {last_item}")
print(f"Updated list: {numbers}")
Output:
Removed item: 40
Updated list: [10, 20, 30]
Here, the pop() method removes and returns the last item (40) from the list. When you don’t provide an index, Python assumes you want the last element.
Example 2: pop() with index
fruits = ['apple', 'banana', 'cherry']
removed_fruit = fruits.pop(1) # Removes the item at index 1
print(f"Removed fruit: {removed_fruit}")
print(f"Updated list: {fruits}")
Output:
Removed fruit: banana
Updated list: ['apple', 'cherry']
In this example, we specify the index 1, and pop() removes the item at that index ('banana').
Edge Cases with Lists:
Empty List: If you try to call pop() on an empty list, Python will raise an IndexError. This happens because there’s no item to remove.
empty_list = []
empty_list.pop() # Raises IndexError: pop from empty list
Invalid Index: If the index you provide doesn’t exist, Python will also raise an IndexError. Always ensure the index is within the range of the list’s length.
numbers = [1, 2, 3]
numbers.pop(5) # Raises IndexError: pop index out of range
Time Complexity:
In dictionaries, use of pop() function is a little different. Instead of using an index, you provide a key, and pop() removes and returns the value associated with that key. You can also provide a default value, which will be returned if the key is missing, preventing errors.
Example: Removing a key-value pair
user_info = {'name': 'Alice', 'age': 30, 'city': 'New York'}
removed_value = user_info.pop('age') # Removes and returns the value for 'age'
print(f"Removed value: {removed_value}")
print(f"Updated dictionary: {user_info}")
Output:
Removed value: 30
Updated dictionary: {'name': 'Alice', 'city': 'New York'}
In this example, pop() removes the 'age' key and returns its value (30).
If the key doesn’t exist in the dictionary, you can either let Python raise a KeyError or specify a default value to avoid the error.
Example with a missing key (no default):
user_info = {'name': 'Alice', 'age': 30}
removed_value = user_info.pop('city') # Raises KeyError because 'city' doesn't exist
Example with a missing key (with default):
user_info = {'name': 'Alice', 'age': 30}
removed_value = user_info.pop('city', 'Not Found') # Returns 'Not Found' if key doesn't exist
print(f"Removed value: {removed_value}")
Output:
Removed value: Not Found
By providing a default value ('Not Found'), you prevent a KeyError and get a controlled response instead.
Behavior with Mutable vs Immutable Values:
Example with mutable value:
user_info = {'name': ['Alice', 'Bob'], 'age': 30}
removed_value = user_info.pop('name') # Removes and returns the list ['Alice', 'Bob']
print(f"Removed value: {removed_value}")
print(f"Updated dictionary: {user_info}")
Output:
Removed value: ['Alice', 'Bob']
Updated dictionary: {'age': 30}
Error Handling with Try/Except:
To prevent crashes when trying to remove a non-existent key, wrap the pop() operation in a try block and catch the KeyError.
user_info = {'name': 'Alice', 'age': 30}
try:
user_info.pop('city') # Key does not exist
except KeyError:
print("Key not found!")
Output:
Key not found!
Python offers several methods for modifying lists, and it's important to understand how pop() compares with others. Knowing when to use each method can improve the clarity and performance of your code.
1. del vs pop()
del: Removes an item at a specified index, but it doesn’t return the value. It can also be used to delete slices of a list.
pop(): Removes and returns the item at the specified index or the last item if no index is given.
numbers = [1, 2, 3]
del numbers[1] # Removes the item at index 1
print(f"List after del: {numbers}")
Output:
List after del: [1, 3]
2. remove() vs pop()
remove(): Removes the first occurrence of a specific value, not by index. It’s useful when you know the value but not the position.
pop(): Removes an item by index and allows you to retrieve the value.
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana') # Removes the first occurrence of 'banana'
print(f"List after remove(): {fruits}")
Output:
List after remove(): ['apple', 'cherry']
3. clear() vs pop()
clear(): Removes all items from the list, leaving it empty.
pop(): Removes a single item at a time.
numbers = [1, 2, 3]
numbers.clear() # Clears the entire list
print(f"List after clear(): {numbers}")
Output:
List after clear(): []
The pop() function is incredibly versatile, whether you're working with lists or dictionaries.
Also Read: Essential Skills and a Step-by-Step Guide to Becoming a Python Developer
Now, let’s look beyond the basics and see how pop compares with other data types.
The pop() function isn't limited to just lists and dictionaries in Python. It’s also used with other data types, like sets and dictionaries (with popitem()), to help you remove items efficiently.
Let’s explore how pop() behaves with these other data types and how it can be useful in different scenarios.
Sets in Python are unordered collections, meaning the items have no specific order. When you use pop() with sets, it removes and returns an arbitrary item. Since there is no guarantee about the order of items in a set, you can't predict which item will be popped.
Unordered Nature of Sets: When you call set.pop(), you won’t know which item is removed. It’s like reaching into a bag of mixed items without being able to see them and pulling one out randomly. This randomness is the key characteristic of sets.
Example: Popping from a Set
my_set = {1, 2, 3, 4, 5}
removed_item = my_set.pop() # Removes an arbitrary item
print(f"Removed item: {removed_item}")
print(f"Updated set: {my_set}")
Output:
Removed item: 1
Updated set: {2, 3, 4, 5}
Here, the pop() function removed 1, but this could have been any item in the set. The important takeaway is that you don't control which item gets removed, and that’s because sets are unordered.
Key Insights:
In dictionaries, there’s another variation of the pop() function called popitem(). This method is similar to pop(), but it’s designed for dictionaries. It removes and returns the last key-value pair inserted in the dictionary. But how this works can vary depending on your Python version.
LIFO vs FIFO Behavior (Pre-3.7 vs Post-3.7 Python Versions):
Use Case Comparison with pop():
Example: popitem() in Python 3.7+
user_info = {'name': 'Alice', 'age': 30, 'city': 'New York'}
removed_item = user_info.popitem() # Removes the last key-value pair
print(f"Removed item: {removed_item}")
print(f"Updated dictionary: {user_info}")
Output:
Removed item: ('city', 'New York')
Updated dictionary: {'name': 'Alice', 'age': 30}
In this example, popitem() removed the 'city' key-value pair because it was the last item added to the dictionary.
Key Insights:
The pop() function is incredibly versatile across different data types. From sets, where it removes a random item, to dictionaries, where you can remove the most recent item with popitem(), it helps manage data efficiently.
Also Read: Data Analysis Using Python: Everything You Need to Know
Now that you’re familiar with the advanced concepts of pop in Python, let’s look at how the pop function in Python is used in real-life programming applications.
The pop() function isn't just a neat trick in Python—it’s a workhorse for many common programming patterns and real-world problems. Whether you're dealing with stacks, queues, or tree traversal, pop() can simplify your code and make it more efficient.
Let’s dive into a few practical scenarios where pop() is especially useful.
Stacks and queues are two fundamental data structures where the pop() function shines. You can use pop() to handle elements in a stack (Last In, First Out - LIFO) or a queue (First In, First Out - FIFO, with a twist).
Stack: A stack uses pop() to remove the most recently added item.
Example: Implementing a Basic Stack
stack = []
stack.append(1) # Push 1
stack.append(2) # Push 2
stack.append(3) # Push 3
top_item = stack.pop() # Removes 3, the top item
print(f"Top item: {top_item}")
print(f"Stack after pop: {stack}")
Output:
Top item: 3
Stack after pop: [1, 2]
Here, pop() removes and returns the last item added to the stack.
Queue: A queue uses pop(0) to remove the first item, but keep in mind that this can be inefficient for large lists due to shifting elements.
Queue Example:
queue = [1, 2, 3, 4]
first_item = queue.pop(0) # Removes the first item
print(f"First item: {first_item}")
print(f"Queue after pop: {queue}")
Output:
First item: 1
Queue after pop: [2, 3, 4]
Cost of pop(0): This operation is O(n) because all the remaining elements in the list need to shift. If performance is a concern, consider using deque for O(1) time complexity.
When it comes to traversing data structures like trees and graphs, pop() becomes your ally in efficiently processing nodes or vertices, especially when doing depth-first search (DFS) or managing a stack of nodes.
Depth-First Search (DFS): You can implement DFS using a stack, and pop() is used to pull elements off the stack as you explore nodes.
Example: Depth-First Search Using List pop()
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': [],
'F': []
}
def dfs(graph, start):
visited = set()
stack = [start]
while stack:
node = stack.pop() # Remove and return the last element
if node not in visited:
print(node, end=" ")
visited.add(node)
stack.extend(graph[node]) # Add adjacent nodes
print()
dfs(graph, 'A')
Output:
A B D E C F
Here, pop() helps in backtracking during the traversal of the graph, allowing the function to explore all nodes in a depth-first manner.
In data cleaning and transformation tasks, pop() is especially helpful for removing items during iteration or modifying dictionaries based on conditions.
Removing items during iteration: If you're cleaning data, you can use pop() to remove and process elements one by one.
Example: Removing Items During Iteration
data = [5, 3, 8, 1, 4]
while data:
item = data.pop()
if item % 2 == 0: # Process even numbers
print(f"Processing even number: {item}")
Output:
Processing even number: 4
Processing even number: 8
Here, pop() removes and processes elements one by one, which can be useful when you need to filter or transform data during iteration.
Dictionary Data Parsing: You can remove keys from a dictionary on certain conditions using pop().
Example: Removing Keys from Dictionary Based on Condition
user_data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
age = user_data.pop('age', None) # Remove 'age' key
print(f"Age: {age}")
print(f"Updated data: {user_data}")
Output:
Age: 30
Updated data: {'name': 'Alice', 'city': 'New York'}
In this case, pop() is used to safely remove the age key if it exists, and return a default value (None) if it doesn’t.
In competitive coding, problems often require manipulating collections or managing sequences of operations. pop() helps you simplify the logic and make your code more efficient.
Example Problem: Reverse a String Using Stack
One common problem in interviews is to reverse a string using a stack. By pushing characters onto a stack and popping them off, you can reverse the order.
Code Snippet: Reversing a String Using a Stack
def reverse_string(s):
stack = list(s)
reversed_str = ''
while stack:
reversed_str += stack.pop()
return reversed_str
print(reverse_string("Python"))
Output:
nohtyP
Here, pop() makes it easy to reverse the string by removing characters from the stack, which is built in LIFO order.
Simplifying Logic: In many problems, pop() can simplify the solution by removing the need for complex indexing or shifting operations. It allows you to focus on the logic without worrying about manually tracking indices.
In each of these scenarios, pop() simplifies complex tasks, helping you write more efficient, readable, and effective Python code.
Also Read: 50 Python Project Ideas With Source Code [2025 Guide]
Next, let’s explore some of the common challenges of pop function and how to overcome them.
While the pop() function is extremely useful, there are a few challenges and limitations that you should keep in mind. Understanding these pitfalls will help you use pop() more effectively and avoid potential issues in your code.
Here are some drawbacks with corresponding solutions:
Drawback |
Solution |
1. Raises IndexError or KeyError on empty list or non-existent key | Use try/except to handle exceptions, or provide a default value to prevent errors. |
2. Inefficient when popping from the beginning of a large list (O(n)) | Use deque from the collections module for O(1) operations at both ends of the list. |
3. Not suitable for immutable structures (e.g., tuples) | Use lists or other mutable collections, or convert the tuple to a list if modification is needed. |
4. Removes items in an arbitrary order from sets | If order matters, use a different data structure, such as a list, or maintain explicit order. |
5. Not ideal for fixed-size structures (e.g., arrays in other languages) | For fixed-size collections, consider other methods (e.g., manually shifting items or using stacks). |
Also Read: 50 Python Project Ideas With Source Code [2025 Guide]
When working with large data structures, you may encounter performance issues, especially if you frequently use pop() in scenarios where efficiency is critical. Understanding the performance implications can help you choose the best approach for your situation.
1. Performance with Large Data Structures
Lists: As mentioned, calling pop() on the last item is fast (O(1)), but popping from the front of a large list is slower (O(n)) because all elements need to shift.
If you need to frequently pop the first element, consider using a deque (from the collections module), which is optimized for fast popping from both ends.
Example (Deque for Fast Pop from Front):
from collections import deque
dq = deque([1, 2, 3, 4])
dq.popleft() # Fast O(1) operation
Output:
deque([2, 3, 4])
Dictionaries: The pop() method is O(1) in dictionaries, but if you're using popitem() in versions of Python before 3.7, there’s no guarantee about the order of removal. In Python 3.7 and later, dictionaries preserve the insertion order, so popitem() is predictable and efficient for removing the last inserted item.
2. Alternative Approaches for Performance-Critical Code
Using deque for Large Lists: If you're performing many insertions and deletions at both ends of the list, a deque provides O(1) performance for these operations.
Use heapq for Priority Queues: If your task involves constantly popping the smallest or largest element, consider using a heap-based priority queue from the heapq module, which offers O(log n) performance for pops.
Key Takeaways:
Whether you're working with lists, sets, or dictionaries, knowing the right tool for the job will ensure your code runs smoothly even under heavy load.
Also Read: Top 15 Python Challenges for Beginners with Examples
With a solid understanding of pop in Python, the next step is advancing your career in programming. Let’s explore how upGrad can help you deepen your knowledge of advanced Python functions.
Learning Python and its functions is crucial for a programming career. They are crucial for tasks like data management, stack implementations, and removing elements dynamically.
To enhance your Python skills, consider diving into projects and coding challenges that require you to use functions like pop() in varied scenarios. Practical applications and hands-on coding experience are the best way to solidify your understanding.
Here are some courses to help you master Python functions:
If you're ready to take the next step in your programming journey, connect with upGrad’s career counseling for personalized guidance. You can also visit a nearby upGrad center for hands-on training to enhance your skills and open up new career opportunities!
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
References:
https://survey.stackoverflow.co/2023/
https://realpython.com/python-news-march-2025/
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources