Lambda functions in Python are concise, anonymous functions that allow you to perform small, one-line operations without using the def
In this lesson, we will explore the syntax, examples, and best use cases for lambda functions.
Syntax of Lambda functions
The general syntax for a lambda function is as follows:
lambda arguments: expression
Explanation:
Keyword: This marks the beginning of a lambda function.lambda
: A comma-separated list of parameters (just like in regular functions). Lambda functions can accept multiple arguments.arguments
: A single expression evaluated and returned by the lambda function. Unlike regular functions, there is noexpression keyword—the result is automatically returned.return
Examples of Lambda functions
Let’s dive into some examples to understand how lambda functions work.
a. Simple Lambda function
# A lambda function that adds 10 to the input number
add_ten = lambda x: x + 10
result = add_ten(5) # Calling the lambda function
print(result) # Output: 15
Explanation:
- The lambda function
takes one argumentadd_ten
and returnsx
.x + 10
- When called with
, it returns5
.15
b. Lambda function with multiple arguments
# A lambda function that multiplies two numbers
multiply = lambda x, y: x * y
result = multiply(4, 5) # Calling the lambda function
print(result) # Output: 20
Explanation:
- The lambda function
takes two argumentsmultiply
andx
and returns their product.y
- When called with
and4
, it returns5
.20
c. Using Lambda functions in higher-order functions
Lambda functions are frequently used in combination with higher-order functions like map()
filter()
reduce()
Example with map()
:
# Using lambda with map to square each number in a list
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
Explanation:
- The lambda function takes one argument
and returnsx
(x squared).x ** 2
- The
function applies this lambda function to each element in themap()
numbers
list, producing a new list of squared values.
When to use Lambda functions
Lambda functions are particularly useful in the following scenarios:
-
Short, Temporary Functions: When you need a small, unnamed function for a brief task, such as passing it as an argument to another function.
-
Functional programming: Lambda functions are often used in functional programming contexts with functions like
,map()
, andfilter()
.reduce()
-
Inline operations: When defining a full function using
def
would be excessive for simple, one-liner operations.
Limitations of Lambda functions
While lambda functions are powerful, they come with some restrictions:
-
Single Expression Only: A lambda function can only contain a single expression and cannot include multiple lines or statements.
-
No Name: Lambda functions are anonymous, which makes them harder to debug or reuse compared to named functions.
-
Reduced Readability: Overusing lambda functions can make code less readable, especially when they are complex.