Python Lambda Functions¶
What is a Lambda Function?¶
- A lambda function in Python is an anonymous, one-line function that is defined using the
lambda
keyword. These functions are primarily used for small, concise operations without needing a formal function declaration usingdef
.
Syntax:¶
lambda arguments: expression
In [ ]:
cube = lambda x: x ** 3
print(cube(3)) # Output: 27
27
Key Features of Lambda Functions:¶
- They can take any number of arguments but contain only one expression.
- The expression is evaluated and returned when the lambda function is executed.
- Lambda functions have their own local scope and can only access global variables and their parameters.
- They are often used as short-term functions for tasks like sorting, filtering, and simple computations.
Why Use Lambda Functions?¶
1. Short and Concise Code : Lambda functions reduce the need for defining a function using
def
, making the code more compact.2. Useful for Anonymous Functions : Lambda functions are useful in cases where a short-lived function is required, such as inside another function.
3. Best for Functional Programming : They work well with built-in functions like
map()
,filter()
, andsorted()
, which are key elements of functional programming.
Examples of Lambda Functions¶
Basic Lambda Function¶
- A simple lambda function that calculates the cube of a number.
In [ ]:
cube = lambda x: x ** 3
print(cube(3)) # Output: 27
27
Lambda with Multiple Arguments¶
- A lambda function that calculates the area of a rectangle.
In [ ]:
rectangle_area = lambda length, width: length * width
print(rectangle_area(5, 6)) # Output: 30
30
Using Lambda Inside a Function¶
- Lambda functions can be embedded within regular functions to create dynamic function behavior.
In [ ]:
# function returns a lambda function that multiplies input values by a given factor.
def multiplier(factor):
"""Returns a lambda function that multiplies input by a factor."""
return lambda num: num * factor
# Creating a function that triples numbers
triple = multiplier(3)
print(triple(4)) # Output: 12
# Creating a function that quadruples numbers
quadruple = multiplier(4)
print(quadruple(4)) # Output: 16
Using Lambda for Sorting Data¶
- Sorting a list of dictionaries based on the 'score' key using a lambda function.
In [ ]:
students = [
{"name": "Alice", "score": 88},
{"name": "Bob", "score": 75},
{"name": "Charlie", "score": 92}
]
# Sorting based on student scores
students.sort(key=lambda student: student["score"], reverse=True)
print(students)
# Output: [{'name': 'Charlie', 'score': 92}, {'name': 'Alice', 'score': 88}, {'name': 'Bob', 'score': 75}]
[{'name': 'Charlie', 'score': 92}, {'name': 'Alice', 'score': 88}, {'name': 'Bob', 'score': 75}]
Lambda with Higher-Order Functions¶
- Lambda functions are widely used with Python’s built-in higher-order functions such as
map()
,filter()
, andreduce()
.
Using map()
with Lambda¶
- Applying a lambda function to convert a list of temperatures from Celsius to Fahrenheit using
map()
.
In [ ]:
temperatures_celsius = [0, 10, 20, 30, 40]
temperatures_fahrenheit = list(map(lambda c: (c * 9/5) + 32, temperatures_celsius))
print(temperatures_fahrenheit) # Output: [32.0, 50.0, 68.0, 86.0, 104.0]
[32.0, 50.0, 68.0, 86.0, 104.0]
Using filter()
with Lambda¶
- Filtering out numbers greater than 50 from a list.
In [ ]:
numbers = [12, 45, 67, 89, 23, 50, 33]
greater_than_50 = list(filter(lambda x: x > 50, numbers))
print(greater_than_50) # Output: [67, 89]
[67, 89]
Using reduce()
with Lambda¶
- The reduce() function from the functools module applies a lambda function cumulatively to the items in a list.
In [ ]:
from functools import reduce
# Finding the product of all numbers in a list
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 120
120