Purify 12/15


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/2?curriculum_id=4f89dab3d788890003000096#


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 ?: ')
counter=0
input_list=[]

while counter<n:                #inputs list from user
    input_list.append(input())
    counter+=1

print purify(input_list)


#2

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

[4,5,5,4]

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

[4,5,4]

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.


#3

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