Python’s .pop()
method is a powerful and flexible built-in function that allows you to remove and return elements from both lists and dictionaries. This method is especially useful in scenarios where you need to both extract and delete items in a single, efficient operation. Whether you’re implementing a stack (LIFO), managing a queue, cleaning up configuration data, or handling optional dictionary keys, .pop()
provides a straightforward solution.
For a comprehensive overview of Python’s list operations beyond .pop()
, see the tutorial on How to Use List Methods in Python 3.
To learn how to calculate the average of list elements efficiently, check out our guide on Average of List in Python.
To learn how to merge multiple lists into a single sequence, see the tutorial on Concatenate Lists in Python.
To learn how to locate and work with string elements in lists, check out the tutorial on Find a String in a List in Python.
This guide covers everything you need to know about Python’s .pop()
method:
.pop()
works in both lists and dictionaries, including syntax, return values, and error handling.pop()
versus .remove()
and the implications of each.pop()
effectively in real-world scenarios like stacks, queues, config management, and cleanup routinesdel
, popitem()
, and deque
At a glance:
pop()
removes and returns an element by index (default: last item)pop(key, default)
removes and returns a value by key, optionally returning a default if the key is missing.pop()
when you need removal in a single step.get()
when only reading values without mutationTo follow this tutorial, you should be familiar with:
try/except
.pop()
method in Python?.pop()
removes and returns the item at a given index (defaulting to the last item if no index is provided)..pop()
removes and returns the value for a specified key. If the key is not found and a default value is provided, it returns the default instead of raising an error.This dual functionality makes .pop()
a go-to method for many common programming tasks, such as:
.pop()
in Lists vs Dictionarieslist.pop(index=-1)
The list.pop(index=-1)
method accepts an optional integer index to remove an element at the specified position. If you omit the index, it defaults to -1
, removing the last item in constant time (O(1)). Specifying any other index triggers shifting of all subsequent elements, resulting in linear time complexity (O(n)) due to element reallocation.
dict.pop(key, default)
The dict.pop(key, default)
method removes the entry associated with the given key
and returns its value. If the key
is missing, the optional default
value is returned instead of raising KeyError
. Internally, this performs a hash-table lookup and deletion, maintaining average-case constant time complexity (O(1)).
.pop()
Method?Efficiency: The .pop()
method is highly efficient because it combines two actions, removing and retrieving an item into a single, atomic operation. This not only reduces the amount of code you need to write, but also minimizes the computational overhead, making your programs faster and more concise, especially in data processing tasks.
Readability: Using .pop()
in your code makes your intentions explicit to anyone reading it. It signals that you want to both access and remove an item from a collection, which improves code clarity. This self-documenting approach helps other developers quickly understand the logic and purpose behind each operation.
Robust Error Handling: When working with dictionaries, .pop()
offers a built-in way to handle missing keys gracefully by allowing you to specify a default return value. This means your code can avoid raising a KeyError
exception if the key doesn’t exist, leading to more robust, fault-tolerant programs that handle edge cases and unexpected input smoothly.
.pop()
?Use .pop()
when you need to process elements from a list or dictionary and remove them as you go. This is especially useful in algorithms that consume data, such as parsing, filtering, or transforming collections, ensuring that processed items are not revisited or left behind in your data structures.
The .pop()
method is ideal for implementing stacks (Last-In-First-Out) and queues (First-In-First-Out) in Python. For stacks, you can use list.pop()
without an index to remove the last item efficiently. For queues, you can use pop(0)
to remove the first item, though for large queues, consider using collections.deque
for better performance.
When you want to keep your collections clean and free of unused or obsolete data, .pop()
helps by removing items as soon as they are no longer needed. This practice is important in long-running programs or memory-sensitive applications, as it prevents the accumulation of stale data and potential memory leaks.
In dictionaries, .pop(key, default)
allows you to attempt to remove a key and retrieve its value, while providing a fallback if the key does not exist. This approach helps you avoid KeyError
exceptions and makes your code more robust when dealing with optional or unpredictable data sources.
This quick visual table helps you remember what .pop()
does, where it applies, and how it behaves in different data types.
.pop()
with ListsThe .pop()
method in Python lists is a versatile tool for both removing and retrieving elements. This makes it ideal for stack-like operations, queue management, and situations where you need to process and discard elements.
list.pop(index=-1)
IndexError
if the list is empty or the index is out of range.colors = ['red', 'green', 'blue']
print(colors.pop()) # Output: blue (removes the last item)
print(colors.pop(0)) # Output: red (removes the item at index 0)
print(colors) # Output: ['green']
You can use .pop()
to implement stack (LIFO) or queue (FIFO) logic:
# Stack (LIFO)
stack = [1, 2, 3]
print(stack.pop()) # Output: 3
# Queue (FIFO)
queue = [1, 2, 3]
print(queue.pop(0)) # Output: 1
.pop()
Works InternallyUnder the hood, Python lists are dynamic arrays. When .pop()
is called without an index, it performs an O(1) operation by simply truncating the end. However, using .pop(index)
involves shifting elements and has O(n) complexity.
For example:
nums = [10, 20, 30, 40, 50]
nums.pop(2) # Slower than nums.pop() due to element shifting
Use .pop()
without arguments when performance matters and you only need to remove the last item.
.pop()
with DictionariesThe .pop()
method for dictionaries allows you to remove a key and simultaneously retrieve its value. This is particularly useful for mutating dictionaries during data processing, configuration management, or when you want to ensure a key is only used once.
dict.pop(key, default)
KeyError
.settings = {'theme': 'dark', 'lang': 'en'}
print(settings.pop('theme')) # Output: dark
print(settings.pop('timezone', 'UTC')) # Output: UTC (since 'timezone' is missing and UTC is default value)
print(settings) # Output: {'lang': 'en'}
This pattern is common when you want to extract and discard configuration or payload keys:
user_data = {"name": "Alice", "email": "alice@example.com"}
email = user_data.pop("email", None)
print(email) # Output: alice@example.com
print(user_data) # Output: {'name': 'Alice'}
When dealing with third-party API payloads, you may want to extract and discard keys you’re no longer using.
payload = {
"user": "admin",
"token": "abc123",
"meta": {"timestamp": "2025-07-23"}
}
token = payload.pop("token", None)
print(token) # Output: abc123
print(payload) # Output: {'user': 'admin', 'meta': {...}}
.pop()
in Lists and DictionariesUnderstanding how .pop()
behaves across different data structures is key to using it effectively in real-world Python programs. The method provides similar functionality in both lists and dictionaries, yet the way it operates in each case reflects the underlying data model.
.pop()
removes an element based on its position or index. If no index is specified, it removes the last item by default. This is ideal for scenarios where order matters, such as stacks and queues..pop()
removes an item using a key. It also allows specifying a fallback value in case the key is missing, which is particularly useful in defensive programming where the existence of keys can’t always be guaranteed.This duality makes .pop()
a highly versatile method perfect for developers who need a compact, intuitive way to both access and mutate their data collections.
The illustration below summarizes how .pop()
behaves in both types of data structures:
Use this visual cheat sheet as a quick reminder of the syntax, behavior, and best use cases for .pop()
in lists and dictionaries.
.pop()
and .remove()
Understanding the difference between .pop()
and .remove()
is essential when working with lists in Python, as they serve distinct purposes and have different behaviors.
Feature | .pop() |
.remove() |
---|---|---|
Removes by | Index (list), Key (dict) | Value (list only) |
Returns value? | ✅ Yes | ❌ No |
Works on dict? | ✅ Yes (keys only) | ❌ No |
Common use case | Stack behavior, dynamic key cleanup | Deleting a known list value |
.pop()
Use .pop()
when:
# List example
data = [10, 20, 30]
value = data.pop(1) # Removes and returns 20
print(data) # Output: [10, 30]
# Dictionary example
config = {'debug': True, 'port': 8000}
port = config.pop('port', 8080) # Removes and returns 8000
.remove()
Use .remove()
when:
# List example
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana') # Deletes the first occurrence of 'banana'
print(fruits) # Output: ['apple', 'cherry']
Note:
.remove()
only works on lists and raises aValueError
if the value does not exist.
.pop()
is more versatile: it works on both lists and dictionaries and supports retrieval..remove()
is limited to lists and can only delete the first matching value..pop()
offers a default fallback for dictionaries, while .remove()
does not.list.pop()
without an index is O(1), whereas .remove()
and pop(index)
are O(n) due to element shifting..pop()
without arguments.By understanding these differences, you can choose the most appropriate method depending on the use case whether you’re cleaning up data, implementing algorithms, or building dynamic logic.
remove()
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana') # Removes 'banana'
.pop()
The .pop()
method is widely used in real-world scenarios that involve both data retrieval and mutation. Here are some practical examples:
When implementing stack data structures (Last-In, First-Out), .pop()
is the canonical way to remove the top element:
stack = [1, 2, 3]
while stack:
print(stack.pop()) # Output: 3, 2, 1
You can use .pop()
to extract sensitive or used configuration values and remove them from the dictionary:
config = {'token': 'abc123', 'user': 'admin'}
token = config.pop('token', None)
This pattern prevents accidental reuse or leakage of sensitive data.
When dealing with user input or external data, you can safely attempt to pop a key and provide a fallback:
payload = {'id': 42}
value = payload.pop('name', 'anonymous') # Returns 'anonymous'
If you’re implementing a cache with TTL (time to live), .pop()
is useful for removing expired keys while retrieving their value.
cache = {'session1': 'data1', 'session2': 'data2'}
expired = cache.pop('session1', None)
This pattern ensures stale data doesn’t linger in memory.
Error | Cause | Fix |
---|---|---|
IndexError |
Popping from empty list or invalid index | Check the list length first |
KeyError |
Popping a missing dict key without default | Use dict.pop(key, default) |
if my_list:
my_list.pop()
value = my_dict.pop('nonexistent', 'fallback')
.pop()
Use pop()
to retrieve and remove in one step.
When you need to both access an element’s value and simultaneously delete it, .pop()
streamlines your code by combining these operations. This atomic approach reduces redundant lookups, minimizes variables, and ensures items aren’t reused accidentally. It’s ideal for workflows like queue processing, stack management, or one-off key extractions where the item shouldn’t persist after retrieval.
Always specify a default for dictionary pop()
.
Providing a fallback value prevents KeyError
exceptions when keys may be absent. By using dict.pop(key, default)
, your code gracefully handles missing entries, returning a known value instead of halting execution. This defensive programming technique is crucial when working with unpredictable or optional data sources, helping maintain stability in data parsing and configuration logic.
Avoid popping within iteration loops.
Modifying a list or dictionary during a for
loop can lead to skipped items, index errors, or logic flaws due to shifting elements or changing key sets. Instead, use a while
loop, iterate over a copy of the collection, or collect keys first and pop afterward. This preserves consistent iteration and prevents subtle bugs in data-processing routines.
Work on a copy when you need the original intact.
If you must preserve the source collection, create a shallow copy using .copy()
for dictionaries and list(...)
or slicing for lists before calling .pop()
. This isolation prevents unintended side effects on shared data structures, supporting scenarios where the original dataset is required for replay, comparison, or rollback purposes in larger systems.
Prefer get()
when only reading values.
If you don’t need to remove an entry, use dict.get(key, default)
to access values without mutating the data structure. This approach avoids side effects, making your code safer and more predictable, particularly in contexts like validation checks, logging, or conditional reads where data integrity must be maintained.
Log or document .pop()
operations for debugging.
In complex or long-lived systems, tracking when and why items are popped can clarify state changes and simplify troubleshooting. Adding comments or logging statements before and after .pop()
calls records the removed key/value and context, aiding future maintenance and preventing confusion when collectors change shape over time.
.pop()
Works in ListsPython lists are implemented as dynamic arrays. When you call list.pop()
, Python removes and returns the item at the specified index (defaulting to the last item). Here’s what happens under the hood:
pop()
without index: Removes the last element. This is an O(1) operation performed very fast, as it just shortens the array.pop(index)
: Removes the element at the given index. All elements after that index are shifted left by one. This is an O(n) operation in the worst case (when popping from the start).import timeit
lst = list(range(10000))
# Popping from end
print(timeit.timeit('lst.pop()', setup='lst = list(range(10000))', number=10000))
# Popping from start
print(timeit.timeit('lst.pop(0)', setup='lst = list(range(10000))', number=10000))
Tip: Use pop()
without an index for best performance in stack-like (LIFO) scenarios.
You can use negative indices to pop from the end:
nums = [10, 20, 30, 40]
print(nums.pop(-2)) # Output: 30
pop()
only removes from the outer list. For nested lists, you must index into the sublist:
matrix = [[1, 2], [3, 4]]
print(matrix[1].pop()) # Output: 4
print(matrix) # Output: [[1, 2], [3]]
Mutating a list while iterating can cause skipped elements or errors:
lst = [1, 2, 3, 4]
for i in range(len(lst)):
lst.pop() # This is safe (removes from end)
# But this is unsafe:
lst = [1, 2, 3, 4]
for x in lst:
lst.pop(0) # May skip elements or cause logic errors
Best Practice: If you need to pop multiple items, use a while loop:
while lst:
lst.pop()
Always check if the list is non-empty before popping to avoid IndexError
:
if my_list:
my_list.pop()
.pop()
Operates in DictionariesDictionaries in Python 3.7+ preserve insertion order. When you call dict.pop(key)
, Python:
KeyError
if the key is missing (unless a default is provided)pop()
, del
, popitem()
, and get()
Python provides several ways to remove or access items in dictionaries and lists. Understanding their differences helps you choose the right tool for the job.
1. pop(key[, default])
default
to return if the key is missing, avoiding KeyError
.settings = {'timeout': 30}
timeout = settings.pop('timeout', 60) # Returns 30
missing = settings.pop('retry', 3) # Returns 3, no error
2. del dict[key]
KeyError
if the key does not exist.data = {'a': 1, 'b': 2}
del data['a'] # data is now {'b': 2}
3. popitem()
(key, value)
tuple.KeyError
if the dictionary is empty.history = {'step1': True, 'step2': False}
last = history.popitem() # ('step2', False)
4. get(key[, default])
key
if it exists, else returns default
(or None
).config = {'host': 'localhost'}
host = config.get('host') # 'localhost'
port = config.get('port', 80) # 80, config unchanged
By choosing the appropriate method, you can write clearer, more efficient code that handles data removal and access exactly as needed.
To pop from a nested dict, index into the sub-dict:
data = {'user': {'name': 'Alice', 'age': 30}}
name = data['user'].pop('name')
print(name) # Output: Alice
To remove several keys, use a loop or comprehension:
keys_to_remove = ['a', 'b']
for k in keys_to_remove:
d.pop(k, None)
Always provide a default to avoid KeyError
:
value = d.pop('missing', 'default')
.pop()
.pop()
is essential in algorithms that require stack or queue behavior:
# Depth-First Search (DFS) using stack
stack = [start_node]
visited = set()
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
stack.extend(graph[node])
# Breadth-First Search (BFS) using queue
queue = [start_node]
visited = set()
while queue:
node = queue.pop(0)
if node not in visited:
visited.add(node)
queue.extend(graph[node])
When processing data, .pop()
can help extract and remove processed fields:
def clean_payload(payload):
user_id = payload.pop('user_id', None)
timestamp = payload.pop('timestamp', None)
# ... process ...
return user_id, timestamp, payload # payload now has only unprocessed keys
Stacks for undo/redo are often implemented with .pop()
:
undo_stack = ['edit1', 'edit2']
last_action = undo_stack.pop() # Undo last action
Popping large objects from lists or dicts can help free memory, especially in long-running processes.
This section breaks down the performance characteristics of .pop()
and highlights scenarios where alternative techniques or data structures may be more suitable.
.pop()
vs Alternativeslist.pop()
(no index): O(1) for removing the last element which is ideal for stack-like operations.list.pop(0)
or remove()
: O(n) because elements must shift to fill the gap, which can degrade performance on large lists.collections.deque.popleft()
: O(1) removal from the front, making it the preferred choice for queue implementations.dict.pop()
(key): Average-case O(1) lookup and removal, efficient for dynamic key-based deletions..pop()
lst.copy()
or dict.copy()
) if the source must remain unchanged.for
loop; instead, iterate over a snapshot or use a while
loop to pop items.deque
instead for O(1) front and back pops.Python’s built-in list
and dict
types are not safe for concurrent mutations. For multi-threaded scenarios:
queue.Queue
offers synchronized, FIFO operations for producer–consumer patterns.deque
with locks: Combine collections.deque
with threading.Lock
to achieve atomic append/pop operations at both ends..pop()
calls in a threading.Lock
to prevent race conditions and ensure data integrity..pop()
inside list/dict comprehensions, as it can lead to confusing code and side effects..pop()
with custom objects?Yes, if you subclass list
or dict
, you inherit .pop()
. You can also override it for custom behavior.
class MyList(list):
def pop(self, index=-1):
print(f"Popping at {index}")
return super().pop(index)
If other variables reference the same list/dict, popping will affect all references (since they point to the same object).
.pop()
vs Alternatives: Quick Reference TableOperation | Removes | Returns Value | Works on | Order Aware | Error on Missing? | Default Option |
---|---|---|---|---|---|---|
pop() |
Yes | Yes | list/dict | Yes | Yes | Yes (dict) |
remove() |
Yes | No | list | Yes | Yes | No |
del |
Yes | No | list/dict | Yes | Yes | No |
popitem() |
Yes | Yes (tuple) | dict | Yes (LIFO) | Yes (empty) | No |
get() |
No | Yes | dict | N/A | No | Yes |
Sample Solution:
def pop_last_n(lst, n):
return [lst.pop() for _ in range(min(n, len(lst)))]
lst = [1, 2, 3, 4, 5]
print(pop_last_n(lst, 3)) # Output: [5, 4, 3]
print(lst) # Output: [1, 2]
.pop()
do in Python?The .pop()
method in Python removes and returns an element from a list or dictionary. In lists, it takes an optional index and removes the element at that position (default is the last). In dictionaries, it removes the value for a given key. This dual functionality makes .pop()
a handy tool when you need to delete and retrieve in one step.
pop()
and remove()
in Python?pop()
removes an item by index (in lists) or by key (in dictionaries) and returns the value. remove()
deletes the first matching value from a list and does not return it. Unlike pop()
, remove()
doesn’t support dictionaries. If you need both retrieval and deletion, prefer pop()
, use remove()
when deleting by value only.
.pop()
on an empty list or missing key?Using .pop()
on an empty list raises an IndexError
, while calling it on a dictionary with a non-existent key and no default raises a KeyError
. To avoid these, check the list length beforehand or use dict.pop(key, default)
to provide a fallback when the key doesn’t exist.
pop()
do in Python?In stack operations (Last-In-First-Out), pop()
removes the most recently added item. Python lists support this behavior natively using list.pop()
. This is useful for undo mechanisms, recursive parsing, and algorithms like Depth-First Search (DFS). For consistent O(1) stack operations, always use pop()
without an index.
If the string’s position is known, use pop(index)
. If not, use remove()
instead. For example:
names = ['Alice', 'Bob', 'Eve']
names.pop(1) # Removes 'Bob'
Keep in mind that pop()
operates by index and will raise an error if the index is out of range.
If you need to remove characters from strings directly, see the tutorial on Remove a Character from a String in Python.
.pop()
in a loop?Yes, but use caution. Popping items from a list or dictionary while iterating over it can cause skipped elements or unexpected behavior. Use a while
loop instead of for
, or iterate over a copy. This ensures consistent logic and avoids mutating the collection mid-iteration.
.pop()
safe for multi-threaded code?Not directly. Python’s built-in list
and dict
types are not thread-safe when modified concurrently. For safe concurrent access, use thread-safe collections like queue.Queue
or collections.deque
for list like behavior, and wrap dictionary access with locks.
.pop()
?Using list.pop()
without an index is a very fast O(1) operation. In contrast, list.pop(index)
is O(n) because elements after the index must be shifted. For dictionaries, pop()
is typically O(1). If you care about performance with large collections, stick to pop()
without an index, or use collections.deque
for efficient queue-like operations.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Building future-ready infrastructure with Linux, Cloud, and DevOps. Full Stack Developer & System Administrator @ DigitalOcean | GitHub Contributor | Passionate about Docker, PostgreSQL, and Open Source | Exploring NLP & AI-TensorFlow | Nailed over 50+ deployments across production environments.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.