A lambda function in Python is a small, anonymous (nameless) function written in a single line. A lambda function can take any number of arguments, but can only have one expression.
Lambda functions do not use def or a function name.
Syntax :
Python
lambda arguments : expression- accepts any number of arguments
- must contain only one expression
- expression is automatically returned.
Example :
Python
square = lambda n: n * n print(square(5)) #output 25 Using Lambda with map( ) :
Python
nums = [1, 2, 3, 4] result = list(map(lambda x: x * 2, nums)) print(result) #output [2, 4, 6, 8] Using Lambda with fliter( ) :
Python
nums = [1, 2, 3, 4, 5] evens = list(filter(lambda x: x % 2 == 0, nums)) print(evens) #output [2, 4]Using Lambda with sorted( ) :
Python
students = [("Rahul", 20), ("Anita", 18), ("Kiran", 22)] students_sorted = sorted(students, key=lambda s: s[1]) print(students_sorted) #output [('Anita', 18), ('Rahul', 20), ('Kiran', 22)]