Python filter and lambda - How to select elements with a condition

Python built-in function filter removes some items from a list. The following code is to make a new list from an old list choosing multiples of 3.

a = [1, 2, 3, 4, 5, 6]


def mod(x):
    if x % 3 == 0:
        return True
    else:
        return False


b = filter(mod, a)
c = list(b)

print(b)  # <filter object at 0x10da86280>
print(c)  # [3, 6]

The first argument of filter is a function that usually has if-statement and returns boolean. The second argument is a list.

b is a filter object. filter function returns a filter object and if you want to see all the elements of it, use list to convert a filter object to a list (c).

You can not iterate a filter object

You may think "b is a filter but I can get each value from b for loop". But it's incorrect.

a = [1, 2, 3, 4, 5, 6]


def mod(x):
    if x % 3 == 0:
        return True
    else:
        return False


b = filter(mod, a)
c = list(b)

print(b)  # <filter object at 0x10da86280>
print(c)  # [3, 6]

for v in b:
    print(v)

The last code for v in b: means nonsense and nothing is printed. So to get each item from filtered items, convert a filter object to a list.

A filter object is essentially different from generator.

How to remove None or empty list, set, tuple

filter is often used to remove None or empty list from a list.

a = [3, 5, None, '', {}, ()]

b = filter(None, a)
c = list(b)

print(c)  # [3, 5]

Set the first argument None, filter returns a list (precisely filter object) of "non empty" values.

Filter and lambda

The first argument of filter can be a lambda function.

a = [1, 2, 3, 4, 5, 6, 7]

b = filter(lambda x: x % 3 == 0, a)
c = list(b)

print(c)  # [3, 6]

lambda x: x % 3 == 0 is almost equivalent to mod in the above source and x in lambda iterates in a. x % 3 == 0 returns true or false.

Comments

Powered by Markdown

More