Learn about Map, Filter, Reduce, and Lambda with Python

2020-07-27 18:39:18 | #programming #python

Today, we're going to demonstrate some functional programming concepts by introducing you to map, filter, and reduce with Python.

As pure functions, they don't have side effects- which means they don't modify they state of parameters, but instead return new objects. And they iterate through recursion, meaning they repeatedly execute the same function/operation per element.

Python Map

The map function accepts two parameters: a function to perform on each element of an iterable, and an iterable. Because map is a pure function, it does not modify the iterable, but returns a brand new iterable with the modified values. And if you don't utilize break or continue, map will run on every single element, duplicating each of them, so you will need to be aware of the memory requirements of mapping a large collection. If it ends up being too memory-intensive, you may be better off with an old-fashioned for loop.

Try It Yourself


Python Filter

filter also accepts two parameters, but the difference is that the parameterized function you pass in must return a conditional True or False. Filter runs this function against each element, and if it evaluates to True, it stores element into a new iterable. Otherwise, it skips it. This new iterable ges returned at the end of the process. So for example, you can filter over a list of numbers and return a new list that contains only the even numbers:

Try It Yourself


Python Reduce

reduce also accepts a function and an iterable, but instead of returning a new iterable, it returns a single value that represents the cumulative effect of the function running on every single element. In Python 3.x, you need to import reduce by adding the following line to the top of your code: from functools import reduce

Try It Yourself


Python Lambda vs. Normal Functions

Lambda does not belong in the same pure function family as map, filter, and reduce. It's just a shorthand way of performing a function's operations without having to define the function with def.

Try It Yourself



You must log in to comment. Don't have an account? Sign up for free.

Subscribe to Our Newsletter

Would you like to receive free whitepapers and other IT news? Just leave your email address below. You may opt out at any time.

Tell Us About Your Project

Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.

Hire Us

We offer web development, enterprise software development, QA & testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.