Quick Tip: Filter function in Python

This is a really quick post about filtering in Python. In the below, you will see that we have a list of animals. I want to filter that list based on a boolean condition – the name of the animal starts with the letter C: True or False. The resulting filter will return a list of only those animals where the condition is True.

animals = ['Cow', 'Horse', 'Pig', 'Chicken']
filtered_animals = filter(lambda animal: animal.startswith("C") == True, animals)
list(filtered_animals)

In the above, we use a lambda function, which is fine & makes things nice and compact, but they’re not so readable and I am honestly not a big fan of Lambda functions. Why? Well, because my view is, code should be readable even if that means it is less concise. It makes it much easier to support and for others to read and understand your code.

With that in mind, here is how we might achieve the same without a Lambda function:

animals = ['Cow', 'Horse', 'Pig', 'Chicken']

def start(animal):
    if animal.startswith("C"):
        return True
    else:
        return False

filtered_animals2 = filter(start, animals)
list(filtered_animals2)

In the below, we’re now filtering a dictionary. Here we filter our dictionary where field 2 is greater than 200. How does this work? Well, when you pass animals.items() it gets converted into a list of tuples: [(‘Cow’, 111),(‘Horse’, 222) etc…

This means, we can iterate over the list. With each iteration, we select a new tuple. We then select tuple[1] – which is the second field (remember tuples are zero indexed) and we can run our condition against it.

animals = {'Cow': 111, 'Horse': 222, 'Pig': 333, 'Chicken': 444}

filtered_animals3 = filter(lambda t: t[1]>200, animals.items())
list(filtered_animals3)

To make this a bit clearer,. we have have non-Lambda version below; where we run the filter using the limit function and we pass in the animals.items() list of tuples.

animals = {'Cow': 111, 'Horse': 222, 'Pig': 333, 'Chicken': 444}

def limit (animal):
    if animal[1] > 200:
        return True
    else:
        return False 

filtered_animals3 = filter(limit, animals.items())
list(filtered_animals3)

And that is it! A simple guide to a simple feature of Python.

Kodey