In Python, lambda functions offer a concise way to write small, anonymous functions. These are also known as inline functions or throwaway functions. Lambda functions are especially useful when you need a quick function for a short period—typically as an argument to higher-order functions like map()
, filter()
, or sorted()
.
This guide will walk you through the basics of lambda functions, when and how to use them, and provide practical examples to make the concept clear.
1. What is a Lambda Function?
A lambda function is a function defined using the lambda
keyword instead of def
. It can have any number of parameters but only one expression. The result of the expression is automatically returned.
# Syntax:
lambda arguments: expression
2. Basic Example
# Example 1: Add two numbers
add = lambda x, y: x + y
print(add(3, 4)) # Output: 7
This is equivalent to:
def add(x, y):
return x + y
3. Lambda Functions with No Arguments
# Example 2: Lambda with no arguments
say_hello = lambda: "Hello!"
print(say_hello()) # Output: Hello!
4. Lambda Functions Inside Other Functions
Lambda functions can be used inside other functions to encapsulate logic temporarily.
# Example 3: Nested lambda
def multiplier(n):
return lambda x: x * n
double = multiplier(2)
print(double(5)) # Output: 10
5. Lambda with map()
map()
applies a function to every item in an iterable. Lambda makes it cleaner.
# Example 4: Squaring each element
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, nums))
print(squares) # Output: [1, 4, 9, 16]
6. Lambda with filter()
filter()
selects items from a list based on a condition.
# Example 5: Filtering even numbers
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4, 6]
7. Lambda with sorted()
You can use lambda functions to define custom sorting logic.
# Example 6: Sorting tuples by 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)]
8. Lambda vs Regular Function
Aspect | Lambda Function | Regular Function |
---|---|---|
Syntax | Single-line expression | Multi-line code allowed |
Return keyword | Implicit | Explicit |
Name | Usually anonymous | Has a name (defined with def ) |
9. Limitations of Lambda Functions
- Only one expression is allowed (no multiple statements)
- Harder to debug or reuse for complex logic
- Less readable for beginners
10. When to Use Lambda Functions
- For short, simple functions that are used temporarily
- When passing a function as an argument (e.g.,
map()
,filter()
) - To avoid cluttering code with one-time-use function definitions
11. Final Thoughts
Lambda functions are a powerful feature in Python for writing concise and readable code. While they’re not a replacement for regular functions, they’re extremely useful in cases where you need a quick, throwaway function. With practice, you’ll find many opportunities to use them effectively in your Python programs.