Practice Problem 'purify'


#1




It seems that my loop does not iterate over all the elements of a list


def purify(input):
    result = input
    for number in input:
        print number
        if number % 2:
            result.remove(number)    
    return result
    
print purify([1,1,1,1,1])


#2

Hi, @sakib1089 ,

One of the problems with your code is that it modifies result as it iterates through it. That interferes with the sequencing of the iteration.

Instead, you should initialize result as an empty list, and iterate through the original list, currently named input, that is the parameter of the function. Test whether each number from the original list is even, and if it is even, append it to result.

You should change the name of the function parameter, since input is also the name of a Python built in function.

Also reconsider the condition in this if header ...

if number % 2:

When the condition is True, is number even or odd?


#4

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