Python Simplified

Everything You Need to Know About Python Lambda Functions

Python lambda functions resized

Introduction

Before we get into Python Lambda functions, let’s recap what functions are and how they are defined. In Python, the function definition starts with a def keyword, followed by the function name and a colon (:), and finally followed by the body of the function. Refer to the simple example below that returns square of a given number.

				
					>>> def square(num):
>>>     return num**2
				
			

Coming to Lambda Functions, they are not only specific to Python. They exist in other programming languages such as JavaScript, Perl, PHP, R, etc. As the name itself says they are also functions and but don’t exhibit all the properties of normal functions. So what makes Lambda functions special, and how it is useful to you as a developer? Let’s understand everything you need to know about Lambda functions in Python.

Lambda Functions

As mentioned in the official documentation of Python, Lambda functions are syntactic sugar to normal Python functions. Lambda functions are simple one-line expressions that get evaluated and returned by the function.

They are also called lambda expressions, anonymous functions, etc. They are anonymous because they don’t have names assigned to them. 

The syntax for the lambda function is as shown below:

				
					>>> lambda argument: expression
				
			

The syntax above consists of a lambda keyword, argument, and an expression.

lambda function syntax

If we were to rewrite the above function that returns the square of the given number using lambda expressions, it could be written as below. 

				
					>>> lambda x: x**2
				
			

You can see that this one-line expression is simple, effective, and readable. Lambda functions are supposed to be simple one-line expressions; so don’t write complicated functions using lambda (Remember Zen of Python – readability counts).

How to use lambda functions

Having understood what lambda functions are and their syntax, let’s see how to use lambda functions in your program.

Using map, filter, zip and reduce functions

Lambda functions are commonly used with higher-order functions such as map, filter, zip, reduce. etc. Let’s take a simple example for each of these.

map() function

The below code returns the square of each number from 1 to 10 using lambda and map functions. The map function takes two arguments — a function and an iterable. Then the function is applied to each element in the iterable and returns the iterator object.

				
					>>> print( list(map(lambda x: x**2, range(1,11))) )
				
			

filter() function

The below code returns a list of even numbers between 1 to 10 using lambda and filter functions. The filter function takes two arguments — a function and an iterable. Then the function tests each element in the iterable and returns iterator object with only those items that return True.

				
					>>> print( list(filter(lambda x: x%2==0, range(1,11))) )
				
			

zip() function

This returns a list of tuples with the country name and capital by making use of lambda and zip functions. The zip function takes two or more iterables and returns a tuple iterator object with elements from each iterable paired together.

				
					>>> country = ['India', 'USA', 'Germany']
>>> capital = ['New Delhi', 'Washington D.C.', 'Berlin', 'Rome']
>>> print( list(zip(country, capital)) )
[('India', 'New Delhi'), ('USA', 'Washington D.C.'), ('Germany', 'Berlin')]
				
			

reduce() function

And this below function returns the sum of integers from the given list using lambda and reduce functions.

				
					>>> from functools import reduce
>>> num_list = [1,2,3,4,5]
>>> reduce(lambda x, y: x+y, num_list)
15
				
			

Using sorted(), min(), max(), etc

Other than the map, filter, zip, higher-order functions lambdas are also used with other built-in higher-order functions as well such as sorted(), min(), max(), etc. 

Let’s see an example of sorted() with lambda and the key parameter. As you see in the second example, we have sorted based on the length of each element using lambda and the key parameter which is different from the the default behavior of sorted function.

				
					>>> countries = ['India', 'USA', 'UK', 'Germany']

>>> sorted(countries) # default behaviour
['Germany', 'India', 'UK', 'USA']

sorted(countries, key=lambda x: len(x))
>>> ['UK', 'USA', 'India', 'Germany']
				
			

Using Pandas library

Pandas is a very popular Python library for data analysis and it also supports the use of the Lambda function. Lambda functions are extensively used in the Data Science community as well. I personally use lambdas a lot when doing data analysis in Pandas. 

In the below example, 5 is added to each row of the column Age by making use of Pandas apply method and lambda function.

				
					age_list = [10, 15, 20, 25, 30]
df = pd.DataFrame(data=age_list, columns=['Age'])
df['Age'].apply(lambda x: x+5)
				
			
				
					0    15
1    20
2    25
3    30
4    35
Name: Age, dtype: int64
				
			

Using if-else statement

Lambda functions can also be used with if-else statements. Here is a simple example using lambda and if-else on Pandas dataframe. 

				
					import pandas as pd
df = pd.DataFrame(data=range(5), columns=['Numbers'])
df['Numbers'].apply(lambda x: 'Even' if x%2==0 else 'Odd')
				
			
				
					0    Even
1     Odd
2    Even
3     Odd
4    Even
Name: Numbers, dtype: object
				
			

Using _ (underscore) in interactive Environment

In an interactive interpreter-only environment such as Jupyter notebook, IDLE, etc, you can also invoke Lambda functions using _ (underscore) as you can see below. 

				
					>>> lambda x: x**2
>>> _(5)
25

>>> _(6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
				
			

But note that this won’t work if you try to run it as a Python file or you try to use _ second time. You will get below error when you try print(_(6)) immediately after using print(_(5)). That means _underscore works only once immediately after the lambda function definition

Using Immediately Invoked Function Expression (IIFE)

Another way you can invoke the Lambda function is through Immediately Invoked Function Expression (IIFE). However, this is not a recommended use of calling lambda expression. You don’t see this method being used anywhere. I have mentioned this for informational purposes only.

				
					>>> print((lambda x: x**2)(5))
25
				
			

List comprehensions Vs. Lambda functions

This is the most common question among Python developers. Because we can achieve the same task using lambda functions and list comprehensions. So which one do you choose? Well, the answer depends on a lot of factors — your personal choice, the speed, etc. Based on my study, the difference between the execution time for both the methods is negligible. Unless you are working on a critical application you need not worry about the speed. 

Don'ts of lambda functions

Lambda functions don’t support annotations.

Since annotations & Lambdas both use colon(:), Python interpreter will have a hard time understanding what’s happening. You will run into errors if you try annotations for lambda functions.

				
					>>> lambda x: int: x**2
 File "<stdin>", line 1
SyntaxError: illegal target for annotation
				
			

Lambdas must be a single expression only and can’t contain any statement.

If you can print it or assign it to a value, then it’s an expression. Otherwise, it’s a statement. Note that expressions can be expanded into multiple lines but they should remain a single expression. Examples of statements include return, try, assert, for, raise, etc. If the lambda function contains a statement, the program will raise the SyntaxError exception.

Don’t assign a lambda function to a variable.

However, this is commonly used for demonstration. That should be fine. But you as a developer don’t make this mistake. Reason — see the example below. It makes debugging difficult because you get only <lambda> in the error description. It doesn’t show the function name my_func anywhere in the error. 

				
					>>> my_func = lambda x: x/0

>>> my_func(10)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "<stdin>", line 1, in <lambda>
ZeroDivisionError: division by zero
				
			

If you had used a normal function, you would get an error message as below and it clearly mentions the name of the function i.e. my_func. So, it becomes much easier to debug. 

				
					>>> def my_func(x):
        return x/0
        
>>> my_func(10)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "<stdin>", line 2, in my_func
ZeroDivisionError: division by zero
				
			

Conclusion

In this post, you understood what lambda functions are and how to use them effectively in your Python code with examples. Additionally, you have gained knowledge on the don’t of lambda functions. Hope you liked the article. If you have any questions or thoughts do let us know in the comments section.

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on email
Chetan Ambi

Chetan Ambi

A Software Engineer & Team Lead with over 10+ years of IT experience, a Technical Blogger with a passion for cutting edge technology. Currently working in the field of Python, Machine Learning & Data Science. Chetan Ambi holds a Bachelor of Engineering Degree in Computer Science.
Scroll to Top