Python Lambda Functions
What is a Lambda Function in Python?
A lambda function in Python is an anonymous function (a function without a name) used to write small and simple functions in a single line of code.
Syntax of Python Lambda Function:
lambda arguments: expression
- lambda is the keyword
- arguments can be one or more
- expression is the operation performed and returned
Example 1: Basic Lambda Function
square = lambda x: x * x
print(square(5))
Output:
25
Example 2: Lambda with Multiple Arguments
add = lambda a, b: a + b
print(add(10, 20))
Output:
30
Use Lambda with Built-in Functions
Lambda with map()
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)
Output:
[1, 4, 9, 16]
Lambda with filter()
numbers = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
Output:
[2, 4]
Lambda with sorted()
students = [("Alice", 88), ("Bob", 95), ("Charlie", 70)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
Output:
[('Charlie', 70), ('Alice', 88), ('Bob', 95)]
Lambda vs def Function in Python
Feature | lambda | def |
---|---|---|
Named Function | No (anonymous) | Yes |
Multi-line | Only one expression | Supports multi-line |
Use Case | Short, quick operations | Full function definitions |
Limitations of Lambda Functions
- Only one expression allowed
- Cannot have statements (like loops, print, etc.)
- Not suitable for complex logic
Real-Life Use Case Example
Sorting Dictionary by Value
my_dict = {'a': 3, 'b': 1, 'c': 2}
sorted_dict = sorted(my_dict.items(), key=lambda item: item[1])
print(sorted_dict)
Output:
[('b', 1), ('c', 2), ('a', 3)]