Lambda Function in Python with Examples (Full Tutorial)

Lambda Function in Python with Examples (Full Tutorial)

03 Jul 2025
Beginner
3.92K Views
15 min read
Learn with an interactive course and practical hands-on labs

Free Python Programming Course For Beginners

Python lambda functions are anonymous functions that are declared using the lambda keyword. A lambda function can take any number of arguments, but can only have one expression. It is often used with functions like map(), filter(), and reduce() for efficient one-line logic.

In this Python tutorial, we'll get into functions in Python covering aspects like the syntax of Python Lambda Functions, an example of Python Lambda Function, and the application of Lambda Function in Python.

What is a Lambda Function in Python?

  • A kind of anonymous function is called a lambda function.
  • Although a lambda function can only have one expression.
  • It can have an unlimited number of parameters.

Python Lambda Function Syntax:

lambda arguments : expression

Python Lambda Function Example

str1 = 'Scholarhat'
upper = lambda string: string.upper()
print(upper(str1))

Output

SCHOLARHAT

Practical Uses of Lambda Function in Python

In this section, we will learn various uses of the Lambda Function in Python

1. Condition Checking Using Python Lambda Function

Let's elaborate on this in Python Compiler.
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))

Output

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

Explanation:

Here we have done Condition Checking Using the Python lambda function. In the above program, the ‘format_numric’ calls the lambda function, and the num is passed as a parameter to perform operations.

2. List Comprehension using Python Lambda Function

We are generating a new lambda function with a default argument of x (the current item in the iteration) on each iteration within the list comprehension. Afterwards, we use item() to execute the same function object with the default parameter later on in the for loop, obtaining the required value. Consequently, the list of lambda function objects is stored in is_even_list.

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

Output

10
20
30
40

3. if-else using Python Lambda Function

Here, we calculate the maximum of two integers using the Max lambda function.
Max = lambda a, b : a if(a > b) else b
print(Max(4, 10))

Output

10

4. filter() Using lambda() Function

  • Python's filter() function accepts two arguments: a list and a function.
  • With this, you can effectively filter out any element of a "sequence" that the function returns True.
  • This is a little software that takes an input list and returns the odd numbers:
  • Use the filter() and lambda functions to eliminate all odd numbers.
  • If x is not even, lambda x: (x % 2!= 0) yields True; otherwise, it returns False. All odd numbers that produced False are eliminated since filter() only retains elements where it returns True.
que = [5, 7, 33, 97, 54, 64, 77, 23, 74, 62]
 
final_list = list(filter(lambda x: (x % 2 != 0), que))
print(final_list)

Output

[5, 7, 33, 97, 77, 23]

5. Lambda Function using Multiple Statements

Unfortunately, Lambda functions do not allow multiple statements, but, we can create two separate lambda functions and then call the other lambda function as a parameter to the first function, as shown in the program below
List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]]
sortList = lambda x: (sorted(i) for i in x)
secondLargest = lambda x, f : [y[len(y)-2] for y in f(x)]
res = secondLargest(List, sortList)
print(res)

Output

[3, 16, 9]

6. map() with Using lambda() Function

  1. Python's map() function accepts two arguments: a list and a function.
  2. When a lambda function and a list are passed to the function, a new list containing every lambda-modified item that the function returned for each item is returned.
  3. For instance:
  • Use the lambda and map() functions to multiply each entry in a list by two.
  • The lambda function and the "map" function are used in the code to duplicate every element in a list.
  • The updated list with the doubled elements is then printed. Each element from the original list is multiplied by two and displayed in the output.
que = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*3, que))
print(final_list)

Output

[15, 21, 66, 291, 162, 186, 231, 69, 219, 183]

Convert elements to upper case using lambda and map() function

employess = ['daksh', 'heral', 'manish', 'reva']
uppered_employees = list(map(lambda employee: employee.upper(), employess))
print(uppered_employees)

Output

['DAKSH', 'HERAL', 'MANISH', 'REVA']

Explanation:

Here, the program converts a list of employee names to uppercase using a lambda function and the ‘map' function and then it prints the list with the employee names in uppercase. The output shows the employee names in all uppercase letters.

7. The reduce() using lambda() Function

A list's sum of every item using the lambda and reduce() functions

from demo import reduce
que = [33, 11, 50, 80, 50, 100]
sum = reduce((lambda a, b: a + b), que)
print(sum)

Output

324

Explanation

The program performs the sum of elements in a list using the ‘reduce' function from the ‘demo' module. It imports ‘reduce', defines a list, applies a lambda function that adds two elements at a time and prints the sum of all elements in the list.

Difference Between Lambda Functions and the def Keyword

FeatureLambda Functiondef Function
SyntaxSingle-line, inline functionMulti-line, full-function definition
Function NameAnonymous (unless assigned to a variable)Requires a name
Return StatementImplicit return (expression result)Explicit return needed
ComplexitySimple logic onlySupports complex logic and statements
Use CaseShort, throwaway functions (e.g., in map, filter)General-purpose reusable functions

The program defines a function that calculates the cube of a given number (6 in this case) using both the lambda function and the 'def' keyword; it then prints the results; the output for both functions is 216, indicating that they both accomplish the same cube calculation.
def cube(y):
	return y*y*y
lambda_cube = lambda y: y*y*y
print("Using function defined with `def` keyword, cube:", cube(6))
print("Using lambda function, cube:", lambda_cube(6))

Output

Using function defined with `def` keyword, cube: 216
Using lambda function, cube: 216

Explanation:

We have seen that by using both lambda() and def() functions the output will be the same, but let's analyze the difference between lambda() and def() functions.
  • The lambda() function supports single-line statements that return a value, while the def() function supports any number of lines inside a block.
  • The lambda() function is a great choice for performing short operations or data manipulations, while the def() function is good for any cases that require multiple lines of code.
  • The lambda function can decrease code readability, while the def() function eases the readability of code.
  • Conclusion
    In this tutorial, we explored lambda function, Its syntax, and their usage examples. We also combine lambda functions with various inbuilt functions like map(), filter(), and reduce(). We also compared lambda functions with regular def functions to understand when to use each.
    Want to Python Certification? join our Free Python Programming Course

    FAQs

    In the application scenarios that need to scale up rapidly, and scale down to zero when not in demand.

    lambda is a keyword in Python for defining the anonymous function.

     It allows for quicker development.

    Take our Python skill challenge to evaluate yourself!

    In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

    GET FREE CHALLENGE

    Share Article
    About Author
    Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

    Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

    Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
    Live Training - Book Free Demo
    Azure AI Engineer Certification Training
    17 Jul
    07:00AM - 09:00AM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    Accept cookies & close this