Python lambda Function
A lambda
function in Python is an anonymous, inline function used for simple operations. It's ideal for short functions that are used only once or temporarily.
What is a Lambda Function?
- It has no name (anonymous).
- Defined using the
lambda
keyword. - Can have any number of arguments, but only one expression.
- The result of the expression is automatically returned.
Syntax
lambda arguments: expression
Equivalent to:
def function(arguments):
return expression
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(3, 7))
Output:
10
Example 3: Lambda with No Arguments
say_hello = lambda: "Hello!"
print(say_hello())
Output:
Hello!
Example 4: Using Lambda in sorted()
Sort list of tuples by second element:
pairs = [(1, 2), (3, 1), (5, 0)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)
Output:
[(5, 0), (3, 1), (1, 2)]
Example 5: Using Lambda with map()
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)
Output:
[1, 4, 9, 16]
Example 6: Using Lambda with filter()
nums = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)
Output:
[2, 4, 6]
Example 7: Using Lambda with reduce()
from functools import reduce
product = reduce(lambda x, y: x * y, [1, 2, 3, 4])
print(product)
Output:
24
Lambda vs def
Feature | lambda | def |
---|---|---|
Anonymous | Yes | No |
Multiple lines | ❌ No | ✅ Yes |
Returns value | Automatically | Must use return |
Usage | Simple functions | Complex functions |
When Not to Use Lambda
- Avoid lambdas for complex logic.
- Don't use them if code readability matters more.
Practice Task
Convert this function into a lambda:
def double(x):
return x * 2
# Lambda version
double = lambda x: x * 2
print(double(10)) # Output: 20
Summary
- Use
lambda
for quick, small, one-line functions. - Commonly used with functions like
map()
,filter()
,sorted()
, andreduce()
. - Avoid using it for complex logic — use
def
instead.