Purify 12/15



Traceback (most recent call last):
File "python", line 15, in
File "python", line 3, in purify
IndexError: list index out of range

What is list index out of range error?? @mtf

def purify(number_list):
    for i in range(len(number_list)):
        if (number_list[i]%2)!=0:   #checks odd numbers in list
            number_list.remove(number_list[i]) #removes odd numbers from list
    return number_list              #returns even list of numbers

n=input('Length of input list ?: ')

while counter<n:                #inputs list from user

print purify(input_list)


by removing numbers from the list, the list becomes shorter. lets say i have this list:


the items are indexed at 0,1,2,3 agree? but then 5 is encountered, and gets removed:


now, your for loop is still trying to access index 3, but it no longer exist. Causing an index error (index doesn't exist). Then we haven't talked about the index shift causing problems for successive odd numbers.

Remove a dreadful method to solve this problem. Rather append even numbers to a new list.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.