12. purify list index out of range



Getting an error "Oops, try again. Your code looks a bit off--it threw a "list index out of range" error.

I kinda expected the code to just work...

def is_odd(u): #checks if the input is odd, if yes returns true
    if not u%2==0:
        return True
        return False
def purify(x):
    for z in x: #for every entry in x, it should loop? no?
        if is_odd(x[z])==False:
    return hurr2

The fault must be obvious but I've been staring at it for so long I don\t know anymore.




seems a bit off. take a look at your for loop:

for z in x:
   print z

z already contains the numbers in the lists, not the indexes. If you want to use indexes, you should use range:

for z in range(x):
   print x[z]

don't mix this two methods, that can cause trouble


gg, removing the x[] fixed it. I guess I don't grasp these methods.


do you understand why? I recommend run some of the code samples i provided in my answer


I think I do understand why, in the for z in x the z gets the value of the next entry in list x every loop so my first version I was trying to index by the first entry value which was out of bounds.

In the for x in range(z) version x has a "counter" value.

Is that correct?


for z in range(x), don't swap it (x in range(z) is wrong), but yes, range will give a counter, which happens to match the indexes

Sorry, i have to correct a mistake, it should be:

for z in range(0,len(x)):

lists start counting from zero, and it needs to be the length of x to get the right indexes


Below is my Code...
it doesn't work on [4,5,5,4].Why?plz help

def purify(odd_even_list):
for i,n in enumerate(odd_even_list):
if n % 2 != 0:
del odd_even_list[i]
return odd_even_list


because deleting causes indexed to shift, the moment you remove the first 5 the second shifts to the position of the first five, and the loop continues to where was the second 5, but is now a 4

Append even numbers to a new lists


list comprehension hasn't been covered yet, which is more difficult then just appending even number to a new list