Python Filter

Python Filter #

filter(function, iterable) applies a function to a bunch of things, and if any of the things is True, it gets returned.

The applied function can be a logical check of some sort.


numbers = [1, 2, 3, 4, 5]

def is_even(thing):
  if thing % 2 == 0: # oh hi modulo
    return True
  
  return False 
  
evens = filter(is_even, things)
# [2, 4]

This can be simplified with a lambda function:

filter(lambda x: (x % 2 == 0), numbers)

A little trick: use None as the function to return everything that is True when coverted to a boolean.