-4

Trying to create a function which removes odd numbers. When I run this code, it prints out only [2,3,4,5,6,7,8,9]. Is this because the return is cancelling my loop after the first iteration? If so, how can I modify this to run the loop and print out a list with all the odd numbers removed?

def evens(numbers):
    for i in range(len(numbers)):
        if numbers[i] % 2 != 0:
            del numbers[i]
        return numbers

numberlist = [1,2,3,4,5,6,7,8,9]

print evens(numberlist)

Before you all jump to downvoting me for a repeated question... I'm asking why my particular code is broken. And this has uncovered an interesting trip-up which is that using the del method in a loop means you actually need to iterate in reverse.

0

1 Answer 1

1

Indeed, you return after the first loop, change the indentation of the return statement to be one tab less. Further, you should iterate from the end of the list back to the beginning, in order not to run out of range because you're modifying the list (deleting elements) while iterating it.

Modify:

def evens(numbers):
    for i in range(len(numbers), 0):
        if numbers[i] % 2 != 0:
            del numbers[i]
        return numbers

to:

def evens(numbers):
    for i in range(len(numbers)-1, -1, -1): # <-- change the iteration from end to beginning, in order not to run out of index range
        if numbers[i] % 2 != 0:
            del numbers[i]
    return numbers # <-- change in indentation

OUTPUT

[2, 4, 6, 8]
Sign up to request clarification or add additional context in comments.

16 Comments

In fact, you have to iterate in reverse order. Otherwise the del statement will break the intended iteration order.
Yes i thought that would be a fix, but then I get a list index out of range error??
Good catch @HuazuoGao - fixed!
@Dude see the changes above.
@Dude by removing elements you're shortening the list. If you deleted index 7, now index 8 becomes index 7. Which means that when you iterate from zero to the full length and delete elements you'll get index out of bounds error. The way to work around it is start from the end, if you delete index 8 and move on backwards - index 7 will not get affected.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.