Chris Chris - 1 month ago 13
Python Question

How to remove last odd number in a list

I have a list of numbers and I would like to remove the LAST odd number from it. This code works well only when the last odd number is not repeated throughout the list before:

numbers = [1, 7, 2, 34, 8, 7, 2, 5, 14, 22, 93, 48, 76, 15, 7]
odd_numbers = []

def remove_last_odd(numbers):
for n in numbers:
if n % 2 != 0:
odd_numbers.append(n)
numbers.remove(odd_numbers[-1])
return numbers


So instead of removing the last 7, I end up removing the first occurrence of 7 in my "numbers" list.

Can anyone help?

Answer

not the most efficient way but will work:

def remove_last_odd(numbers):
    rnumbers = numbers[::-1]
    for n in rnumbers:
        if n % 2 != 0:  
            rnumbers.remove(n)
            break
    return rnumbers[::-1]

basically do this: reverse list, remove first odd number, reverse again and return.

Comments