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 funlist
['item1', 'item2', 'item3', 'item4']

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

>>> print funlist.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 it 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:

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

Leave a comment

Your email address will not be published. Required fields are marked *