Lambda Function in Python

In this tutorial, we will talk about lambda function in Python. Lambda function in python are one of the most interesting topics as it will give you the power to write a function in a single line. That sounds amazing, how python lambda can do that. The lambda function in Python offers a very elegant method for doing difficult tasks with ease. We will deeply talk about the working and how to use lambda function in python. Lets take the baby steps to our topic “Lambda Function In Python”.

What is Lambda Function in Python?

Anonymous functions, or functions without a name, are what Python Lambda Functions are. As we know, a standard Python function is defined using the def keyword. Like that, Python uses the lambda keyword to define an anonymous function.

Syntax of Lambda Function in Python

The syntax for Python lambda is provided below.

lambda arguments: expression
  • There is only one expression that is evaluated and returned in this function, regardless of the number of parameters.
  • Lambda functions can be used anywhere that function objects are required.
  • The fact that lambda functions are syntactically limited to a single expression must always be kept in mind.
  • In addition to several kinds of expressions in functions, it has a variety of purposes in specific programming disciplines.

Python Lambda Function Example

str1 = 'prepbytes'
# lambda returns a function object
rev_upper = lambda string: string.upper()[::-1]



Explanation: In the example above, we constructed a lambda function called rev upper to reverse and convert a string to uppercase.

Use of Lambda Function in Python

Here, we will see different examples using lambda function in python.

Example 1 of Using a Lambda Function in Python for the checking

format_numeric = lambda num: f"{num:e}" if isinstance(num, int) else f"{num:,.2f}"

print("Int formatting:", format_numeric(1000000))
print("float formatting:", format_numeric(999999.789541235))


Int formatting: 1.000000e+06
float formatting: 999,999.79

Example 2 of Distinguishing Lambda functions from def defined functions
def cube(y):
return yyy
lambda_cube = lambda y: yyy

# using function defined
# using def keyword
print("Using function defined with def keyword, cube:", cube(3))

# using the lambda function
print("Using lambda function, cube:", lambda_cube(3))


Using function defined with def keyword, cube: 27
Using lambda function, cube: 27

The cube() function and lambda cube() function perform identically and as intended, as can be seen in the example above. Let’s examine the case from above in more detail:

  • With lambda function
  • Without lambda function
  • Supports single line statements that return some value.
  • Supports any number of lines inside a function block
  • Good for performing short operations/data manipulations.
  • Good for any cases that require multiple lines of code.
  • Using lambda functions can sometimes reduce the readability of code.
  • We can use comments and function descriptions for easy readability.

Practical Applications of Lambda Function in Python

Let’s see the practice use of python lambda in the coding world.

Example 1: List Comprehension Using Python lambda Function
We’ll use the lambda function and list comprehension in this example.

is_even_list = [lambda arg=x: arg * 10 for x in range(1, 5)]

# iterate on each lambda function
# and invoke the function to get the calculated value
for item in is_even_list:



Explanation: We are generating a new lambda function with the default argument of x on each iteration of the list comprehension (where x is the current item in the iteration). We later call the same function object with the default argument using item() inside the for loop to obtain the desired value. As a result, the list of lambda function objects is stored in its even list.

Example 2: Lambda function in Python with if-else
Here we are using Max lambda function to find the maximum of two integers.

# Example of lambda function using if-else
Max = lambda a, b : a if(a > b) else b
print(Max(1, 2))



Example 3: Python Lambda statements with several lines
Although multiple statements are not permitted in lambda functions, we can create two lambda functions and then call one of them as a parameter to another. Let’s use lambda to search for the second greatest element.

List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]]

# Sort each sublist
sortList = lambda x: (sorted(i) for i in x)

# Get the second largest element
secondLargest = lambda x, f : [y[len(y)-2] for y in f(x)]
res = secondLargest(List, sortList)


[3, 16, 9]

Explained: Each sublist of the given list is sorted in the example above using a lambda function. The second lambda function receives this list as an input and returns the n-2th entry from the sorted list, where n is the length of the sublist.

Along with built-in functions like filter(), map(), and reduce(), lambda functions can be employed. When combined with methods like filter(), map(), and reduce(), etc., lambda functions can unleash their full potential.

Using Python Lambda with the filter Function

Python’s filter() function accepts two arguments: a function and a list. This provides a sophisticated approach to eliminate all the sequence "sequence" components for which the function returns True. The following little program extracts the odd numbers from the input list:

Example 1: Utilize the lambda function and filter() to obtain all odd numbers.
If x is not even, the lambda expression x: (x% 2!= 0) return True or False. Since filter() only retains elements that result in True, all odd numbers that produced False are eliminated.

li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]

final_list = list(filter(lambda x: (x % 2 != 0), li))


[5, 7, 97, 77, 23, 73, 61]

Example 2: Use the lambda and filter() functions to filter out anyone older than 18

# Python 3 code to people above 18 yrs
ages = [13, 90, 17, 59, 21, 60, 5]

adults = list(filter(lambda age: age > 18, ages))



[90, 59, 21, 60]

Using lambda() Function with map()

Python’s map() method accepts two arguments: a function and a list. A new list that contains all the lambda-modified items returned by that function for each item is returned when the function is invoked with a lambda function and a list. Let see one example understanding how to use map function with lambda function in python:

Example 1: Use python lambda and the map function to multiply every element of a list by two.

# Python code to illustrate
# map() with lambda()
# to get double of a list.
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]

final_list = list(map(lambda x: x*2, li))


[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]

Example 2: Utilize lambda and the map() function to convert all list elements to uppercase.

# Python program to demonstrate
# use of lambda() function
# with map() function
animals = ['dog', 'cat', 'parrot', 'rabbit']

# here we intend to change all animal names
# to upper case and return the same
uppered_animals = list(map(lambda animal: animal.upper(), animals))




Using reduce and the lambda function

Python’s reduce() function accepts two arguments: a function and a list. A lambda function and iterable are used to invoke the function, and a new reduced result is returned. This repeatedly operates on the iterable’s pair of pairs. The functools module contains the reduce() method.

Example 1: Using lambda() and reduce(), calculate the sum of all the elements in a list.

# Python code to illustrate
# reduce() with lambda()
# to get sum of a list

from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)



In this case, the outcomes of the preceding two elements are added to the following element, and so on until the last element, as in (((((5+8)+10)+20)+50)+100).

Example 2: Using the lambda and reduce() functions, find the most occurred element in a list.

# python code to demonstrate working of reduce()
# with a lambda function

# importing functools for reduce()
import functools

# initializing list
lis = [1, 3, 5, 6, 2, ]

# using reduce to compute maximum element from list
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))


The maximum element of the list is : 6

Now, we have reached the end of our tutorial about lambda function in python. Here, we had discussed what is the lambda function in python, what is the syntax of python lambda, how to use it, how to use python lambda with filter, reduce and map function. Python lambda function can be applied in a variety of contexts, and its features are leveraged to create code that is clear and uncomplicated. Lambda function in python is one of the curious topics, if you are a beginner then must play with it as that will enhance your coding skills for the greater side.

Leave a Reply

Your email address will not be published. Required fields are marked *