Purify - a more elegant way?


#1

https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/2?curriculum_id=4f89dab3d788890003000096

My code works but I think there should be another way to remove remove odd numbers. I don't like n = [] bit... Any suggestions please?

def purify(x):
    result = []
    for n in x:
        if n % 2 == 0:
            result.append(n)
        else:
            n = []
    return result
print purify([1,2,3,4])

#2

Here, this is a simpler (elegant) but still functional way to do it :slight_smile:

def purify(x):
    result = []
    for n in x:
        if n % 2 == 0:
            result.append(n)
    return result

#3

you could just let out the else bit all together? It will create a new list, kind of pointless.

you could use list comprehension, but this hasn't been covered yet:

def purify(x):
    return [y for y in x if y % 2 == 0]

#4

List comprehension is just beautiful! :sweat_smile: Absolutely DRY.


#5

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