5 Uses of Lambda Functions in Python

Yang Zhou
Yang Zhou
Nov 21, 2020 · 4 min read
5 Uses of Lambda Functions in Python
5 Uses of Lambda Functions in Python

Introduction

The lambda function, which is also called the anonymous function, is one of the core concepts in functional programming.

Python, which supports multi programming paradigms, also gives us a simple way to define a lambda function.

The template of writing the lambda function in Python is:

lambda arguments : expression

It contains three parts:

Because of its simplicity, the lambda functions can make our Python code more elegant in some using scenarios. This post will demonstrate 5 common uses of lambda functions in Python and explain them with interesting examples.

Use 1: Give It a Name and Use It As Normal

If we just need a simple function, lambda is a good choice, since it can be treated as a simpler way to define a function. Therefore, we can give it a name and use it like a normal function.

As the above example shown, the results of add_ten() and lambda_add_ten() methods are identical, but the lambda function can make our code shorter and cleaner.

Use 2: Cooperate With Higher Order Functions

If we can use lambda functions together with higher order functions, such as map(), filter() and reduce(), programs will become elegant.

Let’s answer an interview question for Python developers:

Give you a list as following, can you print all the odd numbers within it?

numbers = [1, 12, 37, 43, 51, 62, 83, 43, 90, 2020]

The question looks simple but it’s enough to separate junior and senior Python developers.

A junior programmer may write some code like the following:

It works and nothing wrong. However, being good is not being great. A senior Python programmer will just need one line of code to do the same:

It looks more elegant, doesn’t it?

Image for post
Image for post
Photo by Clark Tibbs on Unsplash

By the way, the above one-line solution is just for showing how a lambda function can be used. Of course there are other one-line solutions, such as the list comprehension technique:

odd_numbers = [i for i in numbers if i % 2 == 1]

Actually, a list comprehension may more readable than a higher order function cooperated with a lambda function in many cases. More details:

Use 3: Assign to the “Key” Argument

Some built-in methods have the key arguments which give us more flexibility.

For example, when we use sorted() or sort() method to sort an iterable in Python, the key argument determines how to compare two elements in the iterable.

This scenario is also the showtime of lambda functions.

As stated above, if we sort the leaders list by the length of every name, a simple way is passing a lambda function to the key argument.

Another common using scenario is to sort a dictionary by its keys or values.

Use 4: Immediately Invoke It

An immediately invoked function expression (IIFE) is an idiom from JavaScript. The lambda functions in Python support this trick as well. We can immediately run a lambda function as the following:

>>> (lambda x,y:x*y)(2,3)
6

However, for readability and maintainability sake, it’s better to only use this trick in Python’s interactive interpreter.

By the way, if you are familiar with underscore tricks in Python, the following way is also available.

>>> lambda x,y:x*y
<function <lambda> at 0x7fc319102d30>
>>> _(2,3)
6

Use 5: Apply It in Closures

The closure is a powerful functional programming feature which is also available in Python. Since it’s about nested functions, we can use lambda functions to make programs clearer.

The following is an example of using closure:

How can we use the lambda function to simplify the above code?

As the above example shown, when we use nested functions, the lambda function can help us write more readable and clean code.

If you haven’t known closures in Python yet, no worries at all, check out the following tutorial:

Conclusion

The lambda function in Python gives us more flexibility and options to design methods. In a word, we should be familiar with the above five common uses to apply it properly and not overuse it.

Thanks for reading. If you like it, please follow me and check out more great Python tutorials below:

TechToFreedom

Dive into technology, investment and entrepreneurship.

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