Last updated: Apr 8, 2024
Reading timeยท3 min
The Python "IndexError: pop from empty list" occurs when we call the pop()
method on an empty list.
To solve the error, use an if
statement to check if the list is truthy
before using the pop()
method, or check if the list's length is greater than
0
.
Here is an example of how the error occurs.
my_list = [] # โ๏ธ IndexError: pop from empty list result = my_list.pop()
We called the pop()
method on an empty list which caused the error.
One way to avoid the error is to use an if
statement to check if the list is
truthy before using pop()
.
my_list = [] if my_list: result = my_list.pop() print(result) else: print('The list is empty')
You can remove the else
block if you don't need it.
my_list
variable is truthy before calling the pop()
method.All values that are not truthy are considered falsy. The falsy values in Python are:
None
and False
.0
(zero) of any numeric type""
(empty string), ()
(empty tuple), []
(empty list), {}
(empty dictionary), set()
(empty set), range(0)
(empty
range).Empty lists are falsy and lists that contain at least 1
item are truthy.
Alternatively, you can check for the list's length to be more explicit.
my_list = [] if len(my_list) > 0: result = my_list.pop() print(result) else: print('The list is empty')
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).
If the list has a length greater than 0
, we can safely call the pop()
method.
try/except
statement to handle the errorYou can also use a try/except block to handle the error.
my_list = [] try: result = my_list.pop() print(result) except IndexError: # ๐๏ธ this runs print('The list is empty')
If calling the pop()
method on the list raises an IndexError
, the except
block is run where we can handle the error or use the pass
keyword to ignore
it.
Here is an example that uses a pass
statement.
my_list = [] try: result = my_list.pop() print(result) except IndexError: pass
The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.
list.pop()
method works in PythonThe list.pop
method removes the item at the given position in the list and
returns it.
my_list = ['bobby', 'hadz', 'com'] my_list.pop(1) print(my_list) # ๐๏ธ ['bobby', 'com']
The code sample removes and returns the list item at index 1
.
0
, and the last item has an index of -1
or len(a_list) - 1
.If no index is specified, the pop()
method removes and returns the last item
in the list.
my_list = ['bobby', 'hadz', 'com'] my_list.pop() print(my_list) # ๐๏ธ ['bobby', 'hadz']
You can learn more about the related topics by checking out the following tutorials: