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.