Bootstrap FreeKB - Python (Scripting) - Resolve "IndexError: list index out of range"
Python (Scripting) - Resolve "IndexError: list index out of range"

Updated:   |  Python (Scripting) articles

Let's say something like this is being returned.

IndexError: list index out of range

 

One of the most common things that can cause this error is if you attempt to remove an item from a list while iterating over the list in a for loop. For example, let's say you have a list that contains key value pairs and you loop over the list.

#!/usr/bin/python3
my_list = [
        { "name": "bill" },
        { "name": "jane" },
        { "name": "john" },
        { "name": "ally" },
        { "name": "jack" },
        { "name": "jill" }
    ]

for index in range(len(my_list)):
  print(f"index {index} = {my_list[index]['name']}")

 

Something like this should be returned.

index 0 = bill
index 1 = jane
index 2 = john
index 3 = ally
index 4 = jack
index 5 = jill

 

Let's try to remove an index from the list in the for loop.

#!/usr/bin/python3
my_list = [
        { "name": "bill" },
        { "name": "jane" },
        { "name": "john" },
        { "name": "ally" },
        { "name": "jack" },
        { "name": "jill" }
    ]

for index in range(len(my_list)):
  print(f"index {index} = {my_list[index]['name']}")
  if my_list[index]['name'] == 'john':
    print(f"removing index {index}")
    del my_list[index]

 

The exception is raised. Notice also the indexes numbers after the delete are not quite right. jill is index 5 but now jill has index 4.

index 0 = bill
index 1 = jane
index 2 = john
removing index 2
index 3 = jack
index 4 = jill
Traceback (most recent call last):
  File "/usr/local/scripts/demo.py", line 14, in <module>
    print(f"index {index} = {my_list[index]['name']}")
                             ~~~~~~~^^^^^^^
IndexError: list index out of range

 

Long story short, do not remove an index from a list in a for loop.

You can go with a while loop where you basically define how the index in incremented.

#!/usr/bin/python3
import ruamel.yaml
import sys

my_list = [
        { "name": "bill" },
        { "name": "jane" },
        { "name": "john" },
        { "name": "ally" },
        { "name": "jack" },
        { "name": "jill" }
    ]

index = 0
end = len(my_list)

while index < end:
  print(f"index {index} = {my_list[index]['name']}")
  if my_list[index]['name'] == 'john':
    print(f"removing john from my_list")
    del my_list[index]
    end -= 1

  index += 1

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 214e29 in the box below so that we can be sure you are a human.