A lambda function in Python is a small anonymous function defined using the lambda keyword.
- It is used to create quick, single-expression functions without needing to formally define them using def.
Syntax:
lambda arguments: expression
- lambda is the keyword.
- arguments are input parameters (can be more than one).
- expression is the operation or result (only one expression, no statements).
Advantages of Lambda Functions:
- Useful for short, quick functions.
- Helps reduce code clutter when passing functions as arguments.
- Ideal for functional programming use cases.
Limitations of Lambda Functions:
- Only one expression is allowed.
- Cannot contain multiple statements or annotations.
- Less readable for complex logic.
1.) Example: Basic Lambda Function:
- Here, square is a lambda function that takes one input x and returns x * x.
square = lambda x: x * x
print(square(4)) # Output: 16
2.) Example: Lambda Function with Multiple Arguments:
- This lambda takes two arguments and returns their sum.
add = lambda a, b: a + b
print(add(3, 5)) # Output: 8
3.) Example: Lambda with Conditional Expression
- A lambda that returns “Even” if the number is even, otherwise “Odd”:
check_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check_even(7)) # Output: Odd
Common Use Cases of Lambda Functions:
Lambda functions are often used with functions like map(), filter(), and sorted().
- Using with map():
- Applies a lambda to each item in a list.
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
print(squares) # Output: [1, 4, 9, 16]
- Using with filter():
- Filters items based on a condition.
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 = = 0, nums))
print(evens) # Output: [2, 4, 6]
- Using with sorted():
- Sort a list of tuples by the second element.
pairs = [(1, 3), (2, 1), (4, 2)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) # Output: [(2, 1), (4, 2), (1, 3)]