Introduction
Lambda functions in Python are small anonymous functions defined using the lambda
keyword. They can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions are often used for short, simple operations that are passed as arguments to higher-order functions or used in data manipulation.
Syntax
lambda arguments: expression
Example
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
Characteristics of Lambda Functions
- Anonymous: Lambda functions do not have a name.
- Single Expression: They can contain only a single expression.
- Multiple Arguments: They can take multiple arguments.
Use Cases for Lambda Functions
- Inline Functions: When a small function is needed temporarily.
- Higher-Order Functions: Functions that take other functions as arguments.
- Data Manipulation: Operations in functions like
map()
,filter()
, andsorted()
.
Examples of Lambda Functions
Example 1: Basic Lambda Function
square = lambda x: x * x
print(square(4)) # Output: 16
Example 2: Lambda Function with Multiple Arguments
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
Example 3: Lambda Function in map()
The map()
function applies a given function to all items in an input list.
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x * x, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
Example 4: Lambda Function in filter()
The filter()
function constructs an iterator from elements of an iterable for which a function returns true.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]
Example 5: Lambda Function in sorted()
The sorted()
function returns a new sorted list from the elements of any iterable.
points = [(2, 3), (1, 2), (4, 1), (3, 5)]
sorted_points = sorted(points, key=lambda point: point[1])
print(sorted_points) # Output: [(4, 1), (1, 2), (2, 3), (3, 5)]
Example 6: Lambda Function in reduce()
The reduce()
function applies a rolling computation to sequential pairs of values in a list.
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum = reduce(lambda x, y: x + y, numbers)
print(sum) # Output: 15
Using Lambda Functions with Higher-Order Functions
Higher-order functions are functions that can take other functions as arguments. Lambda functions are often used with these to provide inline functionality.
Example 7: Using Lambda with map()
, filter()
, and reduce()
from functools import reduce
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Map: Apply a function to all items in the list
squared = list(map(lambda x: x**2, numbers))
print(f"Squared: {squared}") # Output: Squared: [1, 4, 9, 16, 25]
# Filter: Filter items in the list
even = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Even: {even}") # Output: Even: [2, 4]
# Reduce: Apply a rolling computation to sequential pairs of values
sum_all = reduce(lambda x, y: x + y, numbers)
print(f"Sum: {sum_all}") # Output: Sum: 15
Example 8: Sorting with Lambda Functions
students = [
{'name': 'John', 'age': 25, 'grade': 88},
{'name': 'Jane', 'age': 22, 'grade': 93},
{'name': 'Dave', 'age': 23, 'grade': 85},
]
# Sort by age
sorted_by_age = sorted(students, key=lambda student: student['age'])
print("Sorted by age:", sorted_by_age)
# Sort by grade
sorted_by_grade = sorted(students, key=lambda student: student['grade'], reverse=True)
print("Sorted by grade:", sorted_by_grade)
Output:
Sorted by age: [{'name': 'Jane', 'age': 22, 'grade': 93}, {'name': 'Dave', 'age': 23, 'grade': 85}, {'name': 'John', 'age': 25, 'grade': 88}]
Sorted by grade: [{'name': 'Jane', 'grade': 93, 'age': 22}, {'name': 'John', 'grade': 88, 'age': 25}, {'name': 'Dave', 'grade': 85, 'age': 23}]
Conclusion
Lambda functions in Python are used for writing small, concise, and anonymous functions. They are particularly useful when you need a simple function for a short period and do not want to define a full function using def
. By using lambda functions with higher-order functions like map()
, filter()
, sorted()
, and reduce()
, you can write more concise and readable code. The provided examples demonstrate practical applications of lambda functions in various contexts.