How to use pop() in Python
Learn how to use Python's pop() method with examples, tips, real-world applications, and common error fixes. Master list manipulation.

Python's pop() method is a versatile tool to manipulate lists and dictionaries. It removes an item at a specified index or key and returns it, an essential function for many programming tasks.
In this article, you'll explore various pop() techniques and practical tips. You'll also find real-world applications and debugging advice to help you use the method effectively in your projects.
Basic usage of pop() with lists
fruits = ["apple", "banana", "cherry"]
last_fruit = fruits.pop()
print(f"Removed: {last_fruit}")
print(f"Updated list: {fruits}")--OUTPUT--Removed: cherry
Updated list: ['apple', 'banana']
When you call pop() on a list without an index, it defaults to removing the last item. This behavior is ideal for implementing Last-In, First-Out (LIFO) data structures, which function like a stack of plates.
The method performs two key actions at once:
- It modifies the original
fruitslist in place. - It returns the removed element, which you can then assign to a variable like
last_fruit.
Basic pop() operations
Beyond removing the last item from a list, you can also use the pop() method to target specific elements and work with dictionaries.
Using pop() with a specific index
numbers = [10, 20, 30, 40, 50]
removed_number = numbers.pop(2) # Remove element at index 2
print(f"Removed: {removed_number}")
print(f"Updated list: {numbers}")--OUTPUT--Removed: 30
Updated list: [10, 20, 40, 50]
By passing an integer to pop(), you can remove an element from a specific position. In the example, numbers.pop(2) targets the item at index 2. Because Python lists use zero-based indexing, this is the third element in the list—the number 30.
- The method removes the specified element and returns it.
- All subsequent elements shift to the left to fill the gap, which is why the final list becomes
[10, 20, 40, 50].
Using pop() with dictionaries
user_info = {"name": "Alice", "age": 30, "city": "New York"}
age = user_info.pop("age")
print(f"Removed value: {age}")
print(f"Updated dictionary: {user_info}")--OUTPUT--Removed value: 30
Updated dictionary: {'name': 'Alice', 'city': 'New York'}
For dictionaries, the pop() method operates on keys rather than numerical indices. You must specify which key-value pair to remove by passing the key as an argument, like user_info.pop("age"). This makes it a precise tool for managing dictionary data, complementing other techniques for accessing dictionary elements.
- The method finds the key and removes the entire key-value pair.
- It returns the value associated with the key you removed—in this case,
30. - Just like with lists, the original dictionary is modified directly.
Using pop() with default values
settings = {"theme": "dark", "font_size": 12}
sound = settings.pop("sound_enabled", False) # Key doesn't exist, use default
print(f"Sound setting: {sound}")
print(f"Settings: {settings}")--OUTPUT--Sound setting: False
Settings: {'theme': 'dark', 'font_size': 12}
When working with dictionaries, you can provide a default value to pop() to avoid a KeyError. If the key you're trying to remove—like "sound_enabled"—doesn't exist, your program won't crash.
- Instead, the method returns the default value you provided, which is
Falsein this case. - The original dictionary remains unchanged because no key was found to be removed.
This makes pop() a safe way to handle optional data or settings without extra checks.
Advanced pop() techniques
Beyond simple removal, the pop() method unlocks advanced patterns for data structure implementation, careful iteration, and even working with other collection types.
Implementing a stack with pop()
stack = []
stack.append("first task")
stack.append("second task")
stack.append("third task")
while stack:
current_task = stack.pop()
print(f"Processing: {current_task}")--OUTPUT--Processing: third task
Processing: second task
Processing: first task
A list can function as a stack data structure, thanks to the combination of append() and pop(). In this example, tasks are added to the list using append(), which places them at the end. For more details on adding elements to lists, explore various methods beyond append(). The while stack: loop runs as long as the list isn't empty.
Inside the loop, stack.pop() removes and returns the last item added. This demonstrates the Last-In, First-Out (LIFO) principle.
"third task"is added last, so it's processed first."first task"is added first, so it's processed last.
This pattern is common for managing tasks or operations that need to be handled in reverse order.
Using pop() in a loop with careful indexing
queue = ["task1", "task2", "task3", "task4", "task5"]
# Process and remove items from the front
processed = [queue.pop(0) for _ in range(3)]
print(f"Processed items: {processed}")
print(f"Remaining queue: {queue}")--OUTPUT--Processed items: ['task1', 'task2', 'task3']
Remaining queue: ['task4', 'task5']
By repeatedly calling pop(0), you can process items from the front of a list, mimicking a First-In, First-Out (FIFO) queue. The list comprehension in this example executes queue.pop(0) three times, effectively dequeuing the first three tasks.
- Each call removes the element at index
0and returns it. - The rest of the list's elements must then shift to the left to fill the gap.
This pattern is useful, but be mindful that it can be inefficient for large lists due to the repeated shifting of elements. For different approaches to removing list items, consider other methods that may be more suitable for your specific use case.
Using pop() with sets
unique_numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
sample = []
for _ in range(3):
if unique_numbers:
sample.append(unique_numbers.pop())
print(f"Random sample: {sample}")
print(f"Remaining set: {unique_numbers}")--OUTPUT--Random sample: [10, 1, 5]
Remaining set: {2, 3, 4, 6, 7, 8, 9}
When used on a set, the pop() method removes and returns an arbitrary element. Because sets are unordered, you can't specify which item to remove, nor can you predict which one you'll get. This makes it a handy tool for grabbing a random, unique item from a collection.
- The method modifies the original set in place, just like with lists and dictionaries.
- As the example shows, calling
unique_numbers.pop()repeatedly is an efficient way to pull a random sample from a set.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. Instead of piecing together techniques like pop(), you can use Agent 4 to build complete applications directly from a description.
Describe the app you want to build, and the Agent will take it from an idea to a working product. You can create practical tools that leverage the methods from this article:
- A task management tool that uses a list as a stack, processing the most recently added items first with
pop(). - A configuration utility that safely removes temporary settings from a dictionary, using
pop()with a default value to prevent errors. - A giveaway app that pulls a random winner from a set of unique entries by repeatedly calling
pop().
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
While pop() is powerful, you can run into a few common pitfalls, especially when working with empty collections or very large lists.
Handling IndexError when using pop() on empty lists
Calling pop() on an empty list will raise an IndexError because there are no items to remove. To prevent this, you should always check if the list contains items before attempting to pop from it. A simple if your_list: condition is a clean and Pythonic way to ensure your code doesn't crash.
Preventing KeyError when using dictionary pop()
Similarly, trying to pop() a key that doesn't exist in a dictionary results in a KeyError. The best way to prevent this is by providing a default value as a second argument. For example, my_dict.pop('optional_key', None) will return None if the key isn't found, preventing an error and keeping your program running smoothly.
Avoiding performance issues with pop(0) on large lists
Using pop(0) to remove items from the beginning of a large list can be a performance bottleneck. Each time you call it, Python must shift every remaining element to fill the gap—a slow operation. For tasks that require efficient First-In, First-Out (FIFO) processing, you should use a different data structure. The collections.deque object is specifically designed for this purpose and offers a popleft() method that is far more efficient.
Handling IndexError when using pop() on empty lists
Calling pop() on an empty list is a classic mistake that triggers an IndexError. Your program tries to remove an item that isn't there, causing it to crash. Take a look at the following code to see it happen.
def process_items(items):
while True:
item = items.pop()
print(f"Processing: {item}")
example_list = [1, 2, 3]
process_items(example_list) # Will raise IndexError after 3 iterations
The while True: loop runs indefinitely. After processing all items, it attempts to call items.pop() on the now-empty list, causing the crash. The corrected code below shows how to prevent this from happening.
def process_items(items):
while items: # Check if the list is not empty
item = items.pop()
print(f"Processing: {item}")
example_list = [1, 2, 3]
process_items(example_list) # Safely processes all items
The fix replaces the infinite while True: loop with a simple while items: condition. This is a clean, Pythonic way to avoid the error. Here’s how it works:
- The loop only runs as long as the
itemslist is not empty. - In Python, a non-empty list evaluates to
True, while an empty one evaluates toFalse. - Once the last item is popped, the list becomes empty, the condition becomes
False, and the loop stops safely.
For more complex scenarios involving error management, consider learning about handling multiple exception types to build more robust applications.
Preventing KeyError when using dictionary pop()
Just as with lists, trying to remove something that isn't there causes problems with dictionaries. If you use pop() with a key that doesn't exist, Python raises a KeyError, which immediately stops your program. The following code demonstrates this common issue.
user_data = {"name": "John", "email": "john@example.com"}
phone = user_data.pop("phone") # KeyError: 'phone'
print(f"Phone: {phone}")
print(f"Remaining data: {user_data}")
Since the user_data dictionary doesn't contain a "phone" key, the pop() method has nothing to remove and raises an error. Check out the corrected code below for a simple fix.
user_data = {"name": "John", "email": "john@example.com"}
phone = user_data.pop("phone", "Not provided") # Use default value
print(f"Phone: {phone}")
print(f"Remaining data: {user_data}")
The fix is to provide a default value as a second argument to the pop() method. This is a clean way to handle optional data without needing extra checks.
- When you call
user_data.pop("phone", "Not provided"), the method returns the default value"Not provided"if the key isn't found. - This prevents a
KeyError, so your program doesn't crash. The original dictionary is left untouched since no key was removed.
Avoiding performance issues with pop(0) on large lists
While pop(0) is a handy way to implement a queue, it can seriously slow down your program when used on large lists. Each call forces Python to shift every subsequent element, creating a performance bottleneck. The following code illustrates this problem.
# This becomes slow with large lists
large_queue = list(range(10000))
while large_queue:
item = large_queue.pop(0) # O(n) operation
# Process item
Each time the while loop runs, pop(0) forces the entire list to shift. On a large list, this repeated re-indexing quickly grinds your program to a halt. Check out the code below for a far better approach.
from collections import deque
# Use a deque for efficient pop(0) operations
large_queue = deque(range(10000))
while large_queue:
item = large_queue.popleft() # O(1) operation
# Process item
The best fix is to switch from a list to a collections.deque object. A deque, or double-ended queue, is specifically designed for fast appends and pops from both ends. It's the ideal tool when you need a First-In, First-Out (FIFO) data structure.
- Instead of the slow
pop(0), you use the highly efficientpopleft()method. - This operation runs in constant time, meaning its speed doesn't decrease even with millions of items.
Real-world applications
Putting it all together, the pop() method is essential for building features like task priority queues and processing transaction histories.
Managing a task priority queue with pop()
You can build a task priority queue by first sorting your list of tasks and then using pop(0) to remove and handle the most important item first.
tasks = [("Send email", 1), ("Write report", 3), ("Call client", 2)]
tasks.sort(key=lambda x: x[1]) # Sort by priority (lower number = higher priority)
while tasks:
task, priority = tasks.pop(0) # Process highest priority first
print(f"Completing task: {task} (Priority: {priority})")
This snippet shows how to manage a simple priority queue. The tasks list is first arranged in ascending order of priority using the sort() method. The key=lambda x: x[1] argument is crucial here; it ensures sorting is based on the integer value within each task tuple. For more advanced approaches to implementing priority queues, consider specialized data structures that offer better performance.
The while loop then systematically works through the sorted list.
- It uses
tasks.pop(0)to remove the first item, which is always the highest-priority task. - The task is then unpacked and processed, ensuring important items are handled first.
Processing a transaction history with pop()
The pop() method is also ideal for processing a list of items sequentially, like working through a transaction log one entry at a time.
transactions = [
{"id": 1001, "amount": 200, "processed": False},
{"id": 1002, "amount": 150, "processed": False},
{"id": 1003, "amount": 300, "processed": False}
]
total_processed = 0
while transactions:
current = transactions.pop(0)
total_processed += current["amount"]
print(f"Processed transaction #{current['id']}: ${current['amount']}")
print(f"Total processed: ${total_processed}")
This example shows how to process and clear a list of records while calculating a total. The while transactions: loop runs until the list is empty, ensuring every item is handled exactly once.
- Each iteration uses
transactions.pop(0)to remove and return the first transaction from the list. - The
amountfrom that transaction is then added to thetotal_processedvariable.
This approach effectively consumes the entire list, leaving it empty after all transactions are processed and summed up.
Get started with Replit
Now, turn your knowledge of pop() into a real tool. Tell Replit Agent: "Build a task manager that processes the last item first" or "Create a config tool that safely removes optional settings."
The Agent writes the code, tests for errors, and deploys your app directly from your browser. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



