Lambda Function in Python

Lambda Function in Python

5 mins read1.1K Views Comment
Updated on Feb 3, 2023 16:28 IST

Python allows to create small anonymous function using lambda expression. In this article, we will learn how to work with lambda function in python.



Functions are a simple way to decompose a complex large problem into intellectually manageable chunks. They are the most basic program structure that Python provides to maximize code reuse and minimize redundancy. Python also supports something called lambdas, which are sometimes known as anonymous functions. So, what exactly is a lambda function in Python? That’s what we are going to figure out in this article.

Table of Content

  1. Functions in Python
  2. Introduction: Anonymous (Lambda) Functions in Python
  3. Lambda Function Basics
  4. Examples of Lambda Functions

Functions in Python

Before we get started, let us establish a clear picture of what functions are and why are they important. Functions are a universal programming structure and very important coding tools in any programming language. In technical terms, a function is a set of statements or instructions that perform a certain task, grouped together as a unit, so they can be run more than once in a program. I guess the image below would make things much clearer.


You can see that a function is simply a block of instructions, packaged as a unit, just like a box. The simplest way to package your code is to use it at multiple places at multiple times. Functions are a tool for splitting a complex system into well-defined, meaningful, intellectual pieces.

Besides def statement that you can see above, Python provides an expression that you can use to generate function objects. We call them lambdas. Let’s now explore Python Lambda functions in detail.

Functions in Python
Functions in Python
By Varun Dwarki
Variables in Python
Variables in Python
In this article, we will discuss variables in python, how to name them and how to work with the variables.
Python Lists Practice Programs For Beginners
Python Lists Practice Programs For Beginners
Test your Python Lists knowledge with practice programs! In this blog, we will solve 12 python lists exercises for beginners.

Anonymous (Lambda) Functions in Python

A lambda expression is simply an anonymous function, which is a function without a name. Let’s start with an example. Here, I have a function (defined using def) that calculates the square of a given number.

def square(num):
     """Calculate the square of number."""
     return num ** 2

As you can see the code is very simple and using a full-fledged function declaration just to perform a simple operation is kind of overkill. What if I tell you, you can replace this entire simple function with a single expression that yields the same result? Well, Python allows you to do that using Lambda Expressions.

Lambda Function Basics

In Python, you can create small anonymous functions using Lambda expressions. A lambda expression begins with the keyword lambda, followed by a comma-separated parameter list (exactly like the list of the arguments that you enclose in the function header), a colon and an expression.

*lambda argument1, argument2,… argumentN : expression

Ok! With what we have learned till now, let us try to rewrite the square function that we saw earlier (Example 1) as a lambda function.

#Example 2
square1 = lambda x: x ** 2

Simple right! What exactly is happening here though? The square is assigned a function object that the lambda expression returns.

However, Python limits the body of lambda functions to be a pure expression. In other words, you cannot really make any assignments or use other Python statements such as while, try, etc. in the body of the lambda function. The return values of a lambda function work exactly similar to those created and assigned by defs, except for a few differences that make lambdas useful.

  • Lambdas are expressions, not statements, which is why they can appear in places where a def is not allowed. For example, inside function call’s arguments or a list literal
  • Since lambdas are expressions, you can actually only squeeze in only so much without using statements such as try, while, if, etc. They are designed for coding simple functions

That is all there to lambdas. Let’s now try to master the concept of lambda functions in Python with the help of some interesting examples.

Tutorial – for Loop in Python
Tutorial – for Loop in Python
Let’s read about for Loop in Python in the below tutorial.
Introduction to Python Dictionary (With Examples)
Introduction to Python Dictionary (With Examples)
In this tutorial, you will learn all about Dictionary in Python: creating dictionaries, accessing dictionary items, looping through a dictionary, and other dictionary operations with the help of examples.
Understanding Python Sets (With Examples)
Understanding Python Sets (With Examples)
In this article, you will discuss about Python Sets: creating sets, accessing, adding, and removing set items, looping through a set, and other set operations with the help of examples.

Examples of Lambda Functions

Example 3: Create a lambda function that takes a list of numbers as input and returns back a list of even numbers.

#Example 3
numbers = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
list(filter(lambda a: a % 2 == 0, numbers))

The filter method filters the given sequence, which is the list of numbers (here) and checks if each element in the list is even or not with the help of the lambda function. And lastly, the function list creates a list sequence of the output.

Example 4: Write a lambda expression that will sort a list of words by their reversed spelling. For example, if we have a list of pets: cats, dogs, fishes, rabbits, hamsters, parrots, ferrets. You need to arrange them based on their last letter. The output should be:

[‘fishes’, ‘dogs’, ‘hamsters’, ‘cats’, ‘ferrets’, ‘rabbits’, ‘parrots’]

#Example 4
pets = ['cats', 'dogs', 'fishes', 'rabbits', 'hamsters', 'parrots', 'ferrets']
pets.sort(key=lambda word: word[::-1])

You should not that, since the last letter is ‘s’ for all the items in the list, the sort function considers the letter next to the last one, and so on…

Example 5: Given three sequences of numbers, write a lambda expression using map and zip functions, that will calculate element-wise maximum among these 3 sequences. For example,


X = [6, 7, 1, 5, 3]

Y = [2, 5, 13, 6, 1]

Z = [10, 2, 5, 9, 2]

Output: [10, 7, 13, 9, 3]

#Example 5
X = [6, 7, 1, 5, 3]
Y = [2, 5, 13, 6, 1]
Z = [10, 2, 5, 9, 2]
list_max = map(lambda m: max(*m), zip(X, Y, Z))

Example 6: With the help of an example let us check how defaults work on lambda arguments.

#Example 6
product = (lambda a = 3, b = 2, c = 5: a * b * c)
print("The product is:", product(10, 20))
text = (lambda x="Java", y = " is", z = " my favourite": x + y + z)

You can see for the above example that the default arguments work in lambdas just like they work in def.

Understanding Tuples in Python
Understanding Tuples in Python
In this guide, you will learn all about Tuples in Python: creating tuples, accessing tuple items, looping through a tuple, and other tuple operations with the help of examples.
Slicing in Python
Introduction To Decorators In Python
Introduction To Decorators In Python
In this article, we will discuss in detail about what are python decorator, why we need them and finally how to create python decorators.


In this article, we have briefly discussed lambda function in python with lots of examples to get a clear understanding of how to use lambda function.

Hope this article, will help you in your Data Science journey.


What is Lambda function in Python?

Lambda function is a small anonymous function created using Lambda Expression. It begins with the keyword lambda followed by a comma-separated parameter list, a colon and an expression.

Why do we use Lambda function?

Lambda functions are used when you need function for a short period of time. They are mainly used when the function takes another function as an argument.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio