Skip to Content
Learn Python by Building Data Science Applications
book

Learn Python by Building Data Science Applications

by Philipp Kats, David Katz
August 2019
Beginner
482 pages
12h 56m
English
Packt Publishing
Content preview from Learn Python by Building Data Science Applications

The map, filter, and reduce functions

Other functions that you might find useful with data structures are map, filter, and reduce. These are very useful in conjunction with other functions, such as lambdas.

map runs given functions on every element of the iterable, returning a generator:

>>> data1, data2 = (1, 2, 3, 4, 5), ('A', 'B', 'C', 'D', 'E')>>> list(map(lambda x: x**2, data1))  # converting to list in order to seE results[1, 4, 9, 16, 25]>>> list(map(lambda x: x.lower(), data2))['a', 'b', 'c', 'd', 'e']

Similarly, filter returns a subarray of elements for which the function returns a true or truthy value:

list(filter(lambda x: x > 3, data1))>>> [4, 5]

Finally, reduce—which was moved to the itertools package in Python 3—runs given functions ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python for Data Science

Python for Data Science

Yuli Vasiliev
Introduction to Machine Learning with Python

Introduction to Machine Learning with Python

Andreas C. Müller, Sarah Guido

Publisher Resources

ISBN: 9781789535365Supplemental Content