Python filter function

This is an interesting feature in python. Suppose you have a list of items and you want to apply quick filters such as “greater than x”, “less than x”, “above average”, “below average” on list items, then filter() method makes it quite handy.

Typical syntax of filter function is like filter(some_func_name, list_of_items)

You can also think of applying this method to sort on the basis of size, color, shape or any other attribute of object.

Here is an example:


#!/usr/bin/python3

import statistics

# Score of students
scores = [34, 65, 87, 23 , 67, 90, 54, 12, 72, 50, 29]

print("average score is", statistics.mean(scores))

# filter above average scores
above_avg = list(filter(lambda x: x > statistics.mean(scores), scores))
print("above average scores", above_avg)

# filter below average scores
below_avg = list(filter(lambda x: x < statistics.mean(scores), scores))
print("below average scores", below_avg)

#  filter scores less than passing marks, say 40
not_pass = list(filter(lambda x: x < 40, scores))
print("below pass marks", not_pass)

Output:


./filter.py 
average score is 53
above average scores [65, 87, 67, 90, 54, 72]
below average scores [34, 23, 12, 50, 29]
below pass marks [34, 23, 12, 29]

Practically, you will more often use filters on dictionary objects for example knowing student names who have score above/below average and students who have passed or failed. Here is an example of this:


#!/usr/bin/python3

import statistics

# Score of students

students = { 'Dexter' : 34, 'Popoye' : 65, 'Baloo' : 87, 'Mogali' : 23, 'Peppa' : 67, 'Tiger' : 90, 'Pumba' : 54, 'Timon' : 12, 'Jerry' : 72, 'Tom' : 50, 'McDuck' : 29 }

print("Average Score", statistics.mean(list(students.values())))

# filter above average scores
above_avg = dict(filter(lambda x: x[1] > statistics.mean(list(students.values())), students.items()))
print("Above average scores", above_avg)

# filter below average scores
below_avg = dict(filter(lambda x: x[1] < statistics.mean(list(students.values())), students.items()))
print("Below average scores", below_avg)

#  filter scores less than passing marks, say 40
fail_students = dict(filter(lambda x: x[1] < 40, students.items()))
print("Students scoring less than 40", fail_students)

#  filter scores less than passing marks, say 40
pass_students = dict(filter(lambda x: x[1] > 40, students.items()))
print("Students scoring more than 40", pass_students)

Output


./students.py 
Average Score 53
Above average scores {'Popoye': 65, 'Baloo': 87, 'Peppa': 67, 'Tiger': 90, 'Pumba': 54, 'Jerry': 72}

Below average scores {'Dexter': 34, 'Mogali': 23, 'Timon': 12, 'Tom': 50, 'McDuck': 29}

Students scoring less than 40 {'Dexter': 34, 'Mogali': 23, 'Timon': 12, 'McDuck': 29}

Students scoring more than 40 {'Popoye': 65, 'Baloo': 87, 'Peppa': 67, 'Tiger': 90, 'Pumba': 54, 'Jerry': 72, 'Tom': 50}