How Do You Deal with the Python Error “IndexError: pop index out of range”?

Problem scenario
You have a Python list with n items.  You are getting a "IndexError: pop index out of range" error.  The order that these lists are being printed (used or displayed) is not what you expect.  Your program prints the entire list initially, so you know what to expect.  This IndexError and the order of the items being displayed is not what you expect.  Here is an example:

>>> print(fun_list)
['item1', 'item2', 'item3', 'item4']

>>> print(fun_list.pop(0))
item1
>>> print(fun_list.pop(1))
item3

>>> print(fun_list.pop(2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range

What is wrong?

Root cause
The .pop operation removes the item from the list each time the .pop operation is used.  So the index becomes different because the list itself is different.  Pop is destructive.  The list is mutable.

Solution
Do not use pop.  Print the items via the bracket syntax [] and the 0-based indexing.

Here is an example:

>>> fun_list = ['item1', 'item2', 'item3', 'item4']
>>> print fun_list[0]
item1
>>> print fun_list[1]
item2
>>> print fun_list[2]
item3
>>> print fun_list[3]
item4


Caveat: there are times when the pop operation is useful. If you are getting this error and do not know why, we would recommend avoiding pop.

If you want to learn more about Python, you may want to purchase a book on the subject.

Leave a comment

Your email address will not be published.