Site icon Analytics4All

Python: lambda, map(), reduce(), filter()



One of the guiding principles of Python is simplicity. In fact, you will often see well coded, simplistic Python programs called Pythonic as tribute to the programmer’s talent at crafting clean code.

When I think of Pythonic code, the first thing that comes to my mind is lambda

The best way I can describe lambda is as a short cut function. Look at the function in ln[12]. This function accepts 1 argument “y”.  It then multiplies it by 2 and returns the result.

Now look at ln[13]:


x               = lambda            y        :    y*2


Try your code in our online Python console:  


Let’s build on lambda and introduce a new function: map()

Start with ln[15] :

Now let’s examine ln[16]:


Note: reduce() is now a method of functools module, so you will have to import functools for this to work

Reduce takes all the elements in a list an combines them.

In the example below, x is fed into the lambda function a * b as such:


Try your code in our online Python console:  


Filter allows you to run a set of values through a function and filter out the false results.

Below we filter out all values from x that are less than 0


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT

Last Lesson: Error Handling

Next Lesson: Zip and Unpack

Back to Python Course: Course

Exit mobile version