The list.pop([index]) method removes and returns the item at a specified index position in a list. When called without an index, it defaults to index=-1, removing and returning the very last element in Ο(1) constant time.
Value Removal vs. Index Removal: To remove an item by its value rather than its index, use list.remove(value).
The pop() method is invoked directly on an existing list instance:
removed_item = list.pop([index])
| Parameter | Type | Default | Description |
|---|---|---|---|
index |
int |
-1 |
Optional. The zero-based position of the item to remove. Supports both positive indices (0 to len - 1) and negative indices (e.g. -1 for the last item). |
Return Value: Returns the element removed from the list.
Unlike methods that return None (such as append() or remove()), pop() directly hands you the value that was removed:
tasks = ["Write Documentation", "Review Code", "Deploy Service"]
# 1. Pop without arguments: removes and returns the last element
last_task = tasks.pop()
print("Removed:", last_task)
print("Remaining tasks:", tasks)
# 2. Pop from a specific position (index 0 = first element)
first_task = tasks.pop(0)
print("Removed first:", first_task)
print("Final tasks:", tasks)
Removed: Deploy Service
Remaining tasks: ['Write Documentation', 'Review Code']
Removed first: Write Documentation
Final tasks: ['Review Code']
Negative indices count backward from the end of the list. Index -1 designates the final element, -2 designates the second to last, and so on:
colors = ["Red", "Green", "Blue", "Yellow"]
# Remove the second-to-last item ("Blue")
popped_color = colors.pop(-2)
print("Popped:", popped_color)
print("Remaining colors:", colors)
Popped: Blue
Remaining colors: ['Red', 'Green', 'Yellow']
Calling pop() can raise an IndexError under two specific circumstances:
[].pop() raises IndexError: pop from empty list.items.pop(10) on a list of length 3 raises IndexError: pop index out of range.empty_queue = []
try:
empty_queue.pop()
except IndexError as err:
print("Error caught:", err)
Error caught: pop from empty list
Safe Popping Idiom: Always verify that the list is non-empty before popping:
if tasks:
current_task = tasks.pop()
else:
print("No tasks remaining to process.")
Python offers several ways to delete items from a list. Here is how they differ in usage, error behavior, and return values:
| Operation | Target Identified By | Returns Value? | If Target Missing | Typical Use Case |
|---|---|---|---|---|
list.pop([i]) |
Index (position) | Yes (the removed element) | Raises IndexError |
Consuming elements in LIFO stacks or step-by-step extraction. |
list.remove(x) |
Value (first match) | No (returns None) |
Raises ValueError |
Deleting an item when you know its value but not its index. |
del list[i] |
Index or slice range | No (statement) | Raises IndexError |
Deleting slices (e.g. del items[1:3]) without keeping values. |
list.clear() |
All elements | No (returns None) |
No error (already empty) | Resetting a list to empty while retaining its memory reference. |
Python lists are dynamically-sized arrays stored in contiguous blocks of memory. The performance of pop() depends entirely on where you pop from:
list.pop() or list.pop(-1)): Ο(1) Constant Time.list.pop(0)) or arbitrary index: Ο(n) Linear Time.list.pop(0) to implement a FIFO (First-In, First-Out) queue results in slow Ο(n2) quadratic performance. For high-performance queues, use collections.deque and its popleft() method, which runs in Ο(1) constant time.
Because list.append() and list.pop() both operate on the end of the list in Ο(1) time, Python lists serve as perfect, high-speed LIFO (Last-In, First-Out) stacks:
history_stack = []
# User visits pages (push to stack)
history_stack.append("homepage.html")
history_stack.append("tutorials.html")
history_stack.append("python-list.html")
# User clicks "Back" button (pop from stack)
current_page = history_stack.pop()
print("Navigated back from:", current_page)
print("Previous page is now:", history_stack[-1])
A classic computer science problem is validating that opening and closing brackets match properly. Using a stack with list.append() and list.pop(), we can build a syntax validator verified with unit assertions:
def is_balanced(expression):
stack = []
pairs = {")": "(", "]": "[", "}": "{"}
for char in expression:
if char in "([{":
stack.append(char) # Push opening delimiter
elif char in ")]}":
# If closing delimiter with no open pair, invalid
if not stack:
return False
top = stack.pop() # Pop most recent open delimiter
if top != pairs[char]:
return False # Mismatched bracket type
return len(stack) == 0 # True if all opened brackets were closed
# Unit Assertions
assert is_balanced("({[]})") is True
assert is_balanced("({[)]}") is False
assert is_balanced("(((") is False
assert is_balanced("") is True
assert is_balanced("def calculate(a, b): return (a[0] + b[1])") is True
assert is_balanced("def broken(x: return x)") is False
print("All balanced bracket unit assertions passed successfully!")
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.