12/15 - PURIFY - Code works in IDE, but online an Error occurs


#1


Exercise is 12 of 15 - Purify


ERROR:
List Index out of Range-Error
" Oops, try again.
Your code looks a bit off--it threw a "list index out of range" error. Check the Hint if you need help!"


What I expected to happen was the following (Template-Question): lesson done and get to the next one :slightly_smiling:


def purify(numbers):
    numbers_even = []
    for i in numbers:
        if (i % 2) == 0:
            numbers_even.append(numbers[i-1])
    print(numbers_even)
    return numbers_even

numbers = [1, 2, 3, 4, 5, 6, 7]
purify(numbers)

The Code works, i.e., in Geany (a simple Python-IDE) as even as on shell; new list contains the correct Items (2,4,6)

Maybe you got a tip for me? What do I do wrong or better: how does codecademy (propz to you by this way for your great works! :wink: ) want me to solve the lesson?

Thanks,
BSA


#2

I guess I found the mistake, just not the solution yet.

The code is iterating above the INDEX of the list, not above the value on the Index.
If you put an 0 to the list, it returns 0,2,4,6 - but just if you rub the '-1' on line 5 of the 'i-1', that means, I think so, that the code works for this particular situation, anyhow, but is surely not the solution for the meaning problem.

So I have to find a way to iterate above the VALUE of the INDEX of the list, not the index itself...

Tricky :smiley:

Greets
BSA


#3

You observe correctly that the value and the index are being mixed, which is creating the problem.

# i as index
for i in range(len(numbers)):
    if numbers[i] % 2 == 0:
        numbers_even.append(numbers[i])

Otherwise,

# i as value
for i in numbers:
    if i % 2 == 0:
        numbers_even = i

#4

Hi mtf, thanks! I've found another solution now, but will try yours even after sending this reply.

def purify(numbers):
    numbers_even = []
    for i in numbers:
        if (i % 2) == 0:
            numbers_even.append(i)
    print(numbers_even)
    return numbers_even
numbers = [0, 1, 2, 3, 4, 5, 6, 7]
purify(numbers)

I think the problem in the code was the calling of the list[i] "numbers_even.append(numbers[i])

Thanks for your reply & best greets
BSA


#6

If you don't want the zeros in your result, then add the [ i!=0 ] with the if statement like below.,
if (i % 2) == 0 and i != 0: