IndexError: pop from empty list in Python

avatar

Borislav Hadzhiev

Last updated: Apr 22, 2022

banner

Photo from Unsplash

IndexError: pop from empty list in Python #

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.

indexerror pop from empty list

Here is an example of how the error occurs.

main.py
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().

main.py
my_list = [] if my_list: result = my_list.pop() print(result) else: print('list is empty')

You can remove the else block if you don't need it.

We check if the value stored in the 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:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (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.

main.py
my_list = [] if len(my_list) > 0: result = my_list.pop() print(result) else: print('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).

You can also use a try/except block to handle the error.

main.py
my_list = [] try: result = my_list.pop() print(result) except IndexError: # 👇️ this runs print('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.

The list.pop method removes the item at the given position in the list and returns it.

main.py
my_list = ['one', 'two', 'three'] my_list.pop() print(my_list) # 👉️ ['one', 'two']

If no index is specified, the pop() method removes and returns the last item in the list.

Conclusion #

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.