How to Solve "IndexError: pop from empty list" in Python
The IndexError: pop from empty list
error in Python is straightforward: you're trying to use the pop()
method on a list that has no elements.
This guide explains the cause and, more importantly, how to prevent this error with simple, robust checks.
Why the Error Occurs
The list.pop()
method removes and returns an item from a list. By default, it removes the last item:
my_list = ['tutorial', 'reference', 'com']
last_item = my_list.pop()
print(last_item) # Output: com
print(my_list) # Output: ['tutorial', 'reference']
You can also specify an index to remove a specific item:
my_list = ['tutorial', 'reference', 'com']
second_item = my_list.pop(1) # Remove element at index 1
print(second_item) # Output: reference
However, if the list is empty, there's nothing to remove, and pop()
raises the IndexError
:
my_list = []
# ⛔️ IndexError: pop from empty list
# result = my_list.pop() # This causes the error
Preventing IndexError
with if my_list:
(Recommended)
The most Pythonic and efficient way to prevent this error is to check if the list is empty before calling pop()
. Empty lists are "falsy" in Python, so a simple if
statement works:
my_list = []
if my_list: # Checks if the list is NOT empty
result = my_list.pop()
print(result)
else:
print('The list is empty') # Output: The list is empty
if my_list:
: This is the key. This condition isTrue
ifmy_list
has at least one element, andFalse
if it's empty. This is the best and most concise way to check for an empty list.
Preventing IndexError
with len(my_list)
You can also explicitly check the length of the list:
my_list = []
if len(my_list) > 0: # or, equivalently: if len(my_list):
result = my_list.pop()
print(result)
else:
print('The list is empty') # Output: The list is empty
len(my_list) > 0
: This explicitly checks if the list has any elements. It's functionally equivalent toif my_list:
, but less concise.
Using try-except
(Generally Avoid for This Specific Case)
While you can use a try-except
block to catch the IndexError
, it's generally not recommended for this specific problem. The if
check is simpler and more readable. try-except
is better suited for handling unexpected errors, not predictable situations like an empty list.
my_list = []
try:
result = my_list.pop()
print(result)
except IndexError:
print('The list is empty') # Output: The list is empty
If you do use try-except
, and you don't need to do anything specific in the except
block, use pass
:
my_list = []
try:
result = my_list.pop()
print(result)
except IndexError:
pass # We handled it, just do nothing else