Intermediate Python Knowledge

Higher-Order Functions in Python — map(), filter(), and reduce()

Understand three commonly used higher-order functions

Yong Cui
Yong Cui
May 20, 2020 · 7 min read
Photo by Fonsi Fernández on Unsplash

Mapping Iterables

>>> # Declare a list to be mapped
>>> seasons = ['spring', 'summer', 'fall', 'winter']
>>>
>>> # Map the list with the string's uppercase function
>>> mapped_seasons = map(str.upper, seasons)
>>> mapped_seasons
<map object at 0x10e23a2d0>
>>>
>>> # Convert the map object to a list
>>> upper_seasons = list(mapped_seasons)
>>> upper_seasons
['SPRING', 'SUMMER', 'FALL', 'WINTER']
>>> # Declare a function to calculate the difference 
>>> # between predicted and actual target values
>>> def squared_difference(x, y):
... predicted_y = 3 * x + 5
... difference = predicted_y - y
... return difference * difference
...
>>> # Create the x and y values
>>> x_values = [2, 3, 4, 7]
>>> y_values = [10, 14.5, 18.5, 25]
>>>
>>> # Calculate the differences
>>> differences = list(map(squared_difference, x_values, y_values))
>>> differences
[1, 0.25, 2.25, 1]

Filtering Elements

>>> # Declare a list for filtering
>>> integers = [1, 2, 3, 4, 5, 6, 7]
>>>
>>> # Filter the list
>>> filtered_integers = filter(lambda x: x%2 == 0, integers)
>>> filtered_integers
<filter object at 0x10e26f710>
>>>
>>> # Create the list
>>> even_numbers = list(filtered_integers)
>>> even_numbers
[2, 4, 6]
>>> # Declare a list for filtering
>>> students = {'Aaron': {'phys': 95, 'chem': 80, 'math': 92},
... 'David': {'phys': 99, 'chem': 85, 'math': 92},
... 'John': {'phys': 92, 'chem': 84, 'math': 89},
... 'Danny': {'phys': 93, 'chem': 82, 'math': 91},
... 'Zack': {'phys': 97, 'chem': 86, 'math': 93}}
>>>
>>> # Define a function for filtering
>>> def qualify_student(x):
... _, info = x
... condition0 = info['phys'] > 95
... condition1 = info['chem'] > 83
... condition2 = info['math'] > 90
... return condition0 and condition1 and condition2
...
>>> # Create a dict of qualified students
qualified_students = dict(filter(qualify_student, students.items()))
>>> qualified_students
{'David': {'phys': 99, 'chem': 85, 'math': 92}, 'Zack': {'phys': 97, 'chem': 86, 'math': 93}}

Reduce Elements

>>> # Import the needed module
>>> from functools import reduce
>>>
>>> # Create a list for reducing
>>> primes = [2, 3, 5, 7, 11, 13]
>>>
>>> # Reduce the list
>>> total0 = reduce(lambda x, y: x + y, primes, 1)
>>> total0
42
>>> total1 = reduce(lambda x, y: x + y, primes, 5)
>>> total1
46
>>> # Define a function that uses the reduce() function
>>> def factorial(n):
... return 1 if n < 2 else reduce(lambda x, y: x*y, range(1, n+1))
...
>>> # Create a list consisting of factorials
>>> factorials = [factorial(x) for x in range(10)]
>>> factorials
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> # Import the operator functions
>>> from operator import add, mul
>>>
>>> # Comparisons
>>> reduce(lambda x, y: x+y, [2, 3, 4])
9
>>> reduce(add, [2, 3, 4])
9
>>> reduce(lambda x, y: x*y, [1, 2, 3])
6
>>> reduce(mul, [1, 2, 3])
6

Conclusions

The Startup

Get smarter at building your thing. Join The Startup’s +800K followers.

Yong Cui

Written by

Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Love to write on these technological topics. Follow me @ycui01 on Twitter to get latest articles.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +800K followers.

Yong Cui

Written by

Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Love to write on these technological topics. Follow me @ycui01 on Twitter to get latest articles.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +800K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store