12. purify list index out of range


#1


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

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
    else:
        return False
        
def purify(x):
    hurr2=[] 
    for z in x: #for every entry in x, it should loop? no?
        if is_odd(x[z])==False:
            hurr2.append(x[z])
    return hurr2

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


#2

this:

x[z]

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


#3

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


#4

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


#5

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?


#6

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


#7

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


#8

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


#10

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