list.pop()
Removes and returns an item (default last) from a list (mutates).
item = my_list.pop(index=-1)This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Removes and returns an item (default last) from a list (mutates).
The list.pop([index]) method removes the item at the specified position in a list and returns its value. If no index is provided, pop() defaults to the last item (index -1). In terms of algorithmic complexity, popping from the end of a list is an O(1) operation, making lists efficient for stack implementations (Last-In-First-Out). However, popping from the front (index 0) or the middle is an O(n) operation because Python must shift all subsequent elements one position to the left to maintain a contiguous array. This method modifies the original list in-place and raises an IndexError if the list is empty or the index is out of bounds.
Quick reference
Syntax
item = my_list.pop(index=-1)
Inputs
Parameters
See it in practice
Examples
Stack Behavior (LIFO)
stack = ['action1', 'action2', 'action3']
last_action = stack.pop()
print(last_action)
print(stack)action3 ['action1', 'action2']
Calling pop() without arguments removes and returns the last element, mimicking a stack.
Removing at Specific Index
tasks = ['email', 'code', 'review', 'test']
completed = tasks.pop(1)
print(completed)
print(tasks)code ['email', 'review', 'test']
Passing an index allows you to remove an element from a specific position. Note that items to the right of 'code' are shifted left.
Using the Returned Value
items = [10, 20, 30]
while items:
current = items.pop()
print(f'Processing {current}')Processing 30 Processing 20 Processing 10
Since pop() returns the element, it is commonly used in loops to consume a list until it is empty.
Debug faster
Common Errors
IndexError
Cause: Attempting to pop from an empty list.
Fix: Check if the list is not empty before calling pop(), or use a try-except block.
data = []
if data:
data.pop()
else:
print('List is empty')IndexError
Cause: Providing an index that exceeds the current list range.
Fix: Ensure the index is within the valid range of -len(list) to len(list) - 1.
items = ['a', 'b']
items.pop(5) # Raises IndexErrorRuntime support
Compatibility
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Removes and returns an item (default last) from a list (mutates).
index: Index to remove; default -1 (last).
IndexError: Check if the list is not empty before calling pop(), or use a try-except block. IndexError: Ensure the index is within the valid range of -len(list) to len(list) - 1.