Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: remove odd number from a list

Tags:

python

I wrote a function to remove odd number from a list, like that:

def remove_odd(l):
    for i in l:
        if i % 2 != 0:
            l.remove(i)
    print l
    return l

remove_odd([4,5,4])
remove_odd([4,5,4,7,9,11])
remove_odd([4,5,4,7,9,11,12,13])

It returns:

[4, 4]
[4, 4, 9]
[4, 4, 9, 12]

-> wrong

but when I change to remove even number:

def remove_even(l):
    for i in l:
        if i % 2 == 0:
            l.remove(i)
    print l
    return l

remove_even([4,5,4])
remove_even([4,5,4,7,9,11])
remove_even([4,5,4,7,9,11,12,13])

The answer is OK:

[5]
[5, 7, 9, 11]
[5, 7, 9, 11, 13]

What is wrong with the remove_odd() func? I know people usually create the second list inside the func then append even number to that list, but can we solve this exercise with list.remove() ?

Thank you!

like image 991
neo0 Avatar asked Jan 11 '13 09:01

neo0


People also ask

How to print odd numbers in a list in Python?

Python program to print odd numbers in a List. Given a list of numbers, write a Python program to print all odd numbers in given list. Example: Using for loop : Iterate each element in the list using for loop and check if num % 2 != 0. If the condition satisfies, then only print the number.

How to delete all odd items in a list in Python?

You can delete all odd items in one go using a slice: You cannot delete elements from a list while you iterate over it, because the list iterator doesn't adjust as you delete items. See Loop "Forgets" to Remove Some Items what happens when you try.

How do you find odd numbers in a list in logic?

Logic: 1 Traverse each number in the list by using for...in loop. 2 Check the condition i.e. checks number is divisible by 2 or not – to check ODD, number must not be divisible by 2. 3 If number is not divisible by 2 i.e. ODD number from the list, use list.remove () method.

How to delete all the elements from a list with odd frequency?

Below are the ways to delete all the elements from a given list that has an odd frequency: Take a dictionary and initialize it to empty using the {} or dict () say freqncyDictionary. Give the list as static input and store it in a variable.


1 Answers

Your function is working in another way than you would expect. The for loop takes first element, than second etc., so when you remove one element, others change their positions and can be skipped by it (and that happens in your case) when they are preceded by another odd number.

If you insist on using .remove() method, you must operate on a copy instead, like this:

def remove_odd(1):
    for i in l[:]:
        if i % 2 != 0:
            l.remove(i)
    return l

(l[:] is a shallow copy of list l)

However, I think using list comprehension would be much clearer:

def remove_odd(l):
    return [x for x in l if x % 2 == 0]
like image 75
Althorion Avatar answered Nov 08 '22 21:11

Althorion