Search code examples
python-2.7listdel

Python: list index out of range while iterating over a list [using del]


I have encountered the following problem when trying to iterate over this list. There is one argument deleted in the list but the stop of the iteration is the same. I have tried to add a n-1 at the end of the code but that didn't make any difference.

I'm still a newbie so any explanation or help will be truly appreciated.

string_intrare = [['Gheorghe', 'Gita', '8', '7', '5.5', '10'],
['Vuia', 'Vasile', '4', '10', '10', '10'],
['Andreescu', 'Andra', '9', '10', '9', '10'],
['Elenescu', 'Elena', '5', '5', '5', '5']]
n = 4


for i in range(0,n):
    if (float(string_intrare[i][2]) < 5) or (float(string_intrare[i][3]) < 5) or (float(string_intrare[i][4]) < 5) or (float(string_intrare[i][5]) < 5):
        del string_intrare[i]
        print('List ' + str(i) + ' has been removed remove' + ' ===== Grade lower than 5')

Traceback (most recent call last):
  File ".\note_bacalaureat.py", line 16, in <module>
    if (float(string_intrare[i][2]) < 5) or (float(string_intrare[i][3]) < 5) or (float(string_intrare[i][4]) < 5) or (float(string_intrare[i][5]) < 5):
IndexError: list index out of range

Solution

  • This is happening because in case the 'if' condition evaluates to true one of the list items gets deleted and the size of the list is now reduced but n is still the same and the for loop continues to iterate n times.

    One possible way to make it work is this :

    string_intrare = [['Gheorghe', 'Gita', '8', '7', '5.5', '10'],['Vuia', 'Vasile', '4', '10', '10', '10'],['Andreescu', 'Andra', '9', '10', '9', '10'],['Elenescu', 'Elena', '5', '5', '5', '5']]
    n = 4
    
    
    for i in string_intrare:
        if (float(i[2]) < 5) or (float(i[3]) < 5) or (float(i[4]) < 5) or (float(i[5]) < 5):
            print('List ' ,i , ' has been removed remove' , ' ===== Grade lower than 5')
            string_intrare.remove(i)