Python Lambda Functions Complete Guide
Learn all Python lambda function concepts - syntax, map(), filter(), reduce(), sorted() with lambda, and practical applications with examples.
Anonymous
No function name
Single Expression
One-line functions
Functional
map, filter, reduce
Inline
Defined where used
What are Python Lambda Functions?
Lambda functions in Python are small, anonymous functions defined with the lambda keyword. They can have any number of arguments but only one expression, which is evaluated and returned.
Key Concept
Lambda functions are anonymous (no function name), single-expression functions that are typically used for short, simple operations where defining a regular function would be overkill.
# Lambda Function Syntax:
# lambda arguments: expression
# 1. Basic lambda functions
add = lambda x, y: x + y
print(f"5 + 3 = {add(5, 3)}") # 8
square = lambda x: x ** 2
print(f"Square of 4 = {square(4)}") # 16
# 2. Lambda vs regular function
# Regular function
def add_regular(x, y):
return x + y
# Lambda function
add_lambda = lambda x, y: x + y
print(f"Regular: {add_regular(5, 3)}") # 8
print(f"Lambda: {add_lambda(5, 3)}") # 8
# 3. Immediately Invoked Lambda Expression (IIFE)
result = (lambda x, y: x * y)(5, 3)
print(f"Immediately invoked: {result}") # 15
# 4. Lambda with default arguments
multiply = lambda x, y=2: x * y
print(f"5 * 2 = {multiply(5)}") # 10 (uses default)
print(f"5 * 3 = {multiply(5, 3)}") # 15 (override default)
# 5. Lambda with no arguments
get_pi = lambda: 3.14159
print(f"PI = {get_pi()}") # 3.14159
# 6. Lambda with *args (variable arguments)
sum_all = lambda *args: sum(args)
print(f"Sum of 1,2,3,4,5 = {sum_all(1, 2, 3, 4, 5)}") # 15
# 7. Lambda with **kwargs (keyword arguments)
print_kwargs = lambda **kwargs: {k: v for k, v in kwargs.items()}
result = print_kwargs(name="Alice", age=30, city="NYC")
print(f"Keyword args: {result}") # {'name': 'Alice', 'age': 30, 'city': 'NYC'}
# 8. Lambda returning None (no return value)
print_message = lambda msg: print(msg)
print_message("Hello from lambda!") # Hello from lambda!
# 9. Lambda with conditional expression
is_even = lambda x: True if x % 2 == 0 else False
print(f"Is 4 even? {is_even(4)}") # True
print(f"Is 5 even? {is_even(5)}") # False
# Alternative syntax (more Pythonic)
is_even = lambda x: x % 2 == 0
# 10. Chained operations in lambda
process = lambda x: (x + 10) * 2
print(f"Process 5: {process(5)}") # (5 + 10) * 2 = 30
# 11. Lambda with type hints (Python 3.6+)
from typing import Callable
add_typed: Callable[[int, int], int] = lambda x, y: x + y
print(f"Typed lambda: {add_typed(7, 3)}") # 10
Python Lambda Functions Complete Reference
Lambda functions are most powerful when combined with Python's built-in functions. Here's a comprehensive table of lambda function applications.
Complete Lambda Functions Reference Table
| Category | Function/Method | Description | Lambda Example | Result |
|---|---|---|---|---|
| Basic Lambda | Simple Operation | Basic arithmetic operations | lambda x: x * 2 |
Doubles input |
| Basic Lambda | Conditional | Ternary conditional expression | lambda x: 'even' if x%2==0 else 'odd' |
Classifies number |
| Basic Lambda | String Operation | String manipulation | lambda s: s.upper() |
Uppercase string |
| map() Function | Transform List | Apply function to all elements | map(lambda x: x**2, [1,2,3]) |
[1, 4, 9] |
| map() Function | Type Conversion | Convert elements to different type | map(lambda x: str(x), [1,2,3]) |
['1', '2', '3'] |
| map() Function | Multiple Lists | Process multiple lists together | map(lambda x,y: x+y, [1,2], [3,4]) |
[4, 6] |
| filter() Function | Filter Even | Filter even numbers | filter(lambda x: x%2==0, [1,2,3,4]) |
[2, 4] |
| filter() Function | Filter Strings | Filter strings by length | filter(lambda s: len(s)>3, ['a','ab','abc','abcd']) |
['abcd'] |
| filter() Function | Filter Truthy | Remove falsy values | filter(lambda x: x, [0,1,False,True,'']) |
[1, True] |
| reduce() Function | Sum Reduction | Calculate sum of list | reduce(lambda x,y: x+y, [1,2,3,4]) |
10 |
| reduce() Function | Product Reduction | Calculate product of list | reduce(lambda x,y: x*y, [1,2,3,4]) |
24 |
| reduce() Function | Max/Min | Find maximum value | reduce(lambda x,y: x if x>y else y, [1,5,3,9]) |
9 |
| sorted() Function | Sort by Length | Sort strings by length | sorted(['aaa','b','cc'], key=lambda x: len(x)) |
['b','cc','aaa'] |
| sorted() Function | Sort Dictionary | Sort dict by values | sorted(dict.items(), key=lambda x: x[1]) |
Sorted items |
| sorted() Function | Custom Sort | Sort by multiple criteria | sorted(list, key=lambda x: (x[1], x[0])) |
Multi-key sort |
| Advanced | List Comprehension | Lambda in list comprehension | [(lambda x: x*2)(i) for i in range(3)] |
[0, 2, 4] |
| Advanced | Dictionary Key | Lambda as dictionary key function | max(dict, key=lambda k: dict[k]) |
Key with max value |
| Advanced | Closure | Lambda with closure | (lambda x: lambda y: x+y)(5)(3) |
8 |
| Advanced | Function Return | Lambda returning lambda | multiplier = lambda n: lambda x: x*n |
Function factory |
- Use lambda for simple, one-line operations
- Use regular functions for complex logic or multiple lines
- Lambda functions are anonymous - assign to variables only when necessary
- Use
map(),filter(),reduce()with lambda for functional programming - Use
keyparameter insorted(),min(),max()with lambda - Avoid nesting lambdas - they become hard to read
- Consider list comprehensions as alternatives to
map()andfilter()
Python Lambda Functions
A lambda function is a small anonymous function written in a single line.
Syntax
lambda arguments: expression
1. Lambda with map()
map() applies a function to every element in an iterable.
Syntaxmap(function, iterable)
nums = [1, 2, 3, 4]
result = list(map(lambda x: x * x, nums))
print(result)
# Output
# [1, 4, 9, 16]
Explanationlambda x: x * x squares each number. map() applies it to all elements.
2. Lambda with filter()
filter() selects elements based on a condition.
Syntaxfilter(function, iterable)
nums = [1, 2, 3, 4, 5, 6]
result = list(filter(lambda x: x % 2 == 0, nums))
print(result)
# Output
# [2, 4, 6]
Explanationlambda x: x % 2 == 0 checks even numbers. filter() keeps only matching elements.
3. Lambda with reduce()
reduce() repeatedly applies a function to reduce values into one result.
Important: reduce() is available in the functools module.
Syntaxreduce(function, iterable)
from functools import reduce
nums = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, nums)
print(result)
# Output
# 10
# Working
# ((1 + 2) + 3) + 4
4. Lambda with sorted()
sorted() sorts elements using a custom key.
words = ["apple", "kiwi", "banana", "fig"]
result = sorted(words, key=lambda x: len(x))
print(result)
# Output
# ['fig', 'kiwi', 'apple', 'banana']
Explanationlambda x: len(x) sorts based on length.
students = [("Ram", 85), ("Sam", 72), ("John", 90)]
result = sorted(students, key=lambda x: x[1])
print(result)
# Output
# [('Sam', 72), ('Ram', 85), ('John', 90)]
5. Lambda with min()
min() finds the smallest value.
students = [("Ram", 85), ("Sam", 72), ("John", 90)]
result = min(students, key=lambda x: x[1])
print(result)
# Output
# ('Sam', 72)
Explanation
Finds student with minimum marks.
6. Lambda with max()
max() finds the largest value.
students = [("Ram", 85), ("Sam", 72), ("John", 90)]
result = max(students, key=lambda x: x[1])
print(result)
# Output
# ('John', 90)
Explanation
Finds student with maximum marks.
Quick Summary Table
| Function | Purpose | Example |
|---|---|---|
map() | Transform elements | Square numbers |
filter() | Select matching elements | Even numbers |
reduce() | Combine into one value | Sum of list |
sorted() | Custom sorting | Sort by length |
min() | Smallest element | Minimum marks |
max() | Largest element | Maximum marks |
Combined Example
from functools import reduce
nums = [1, 2, 3, 4, 5]
# map
squares = list(map(lambda x: x*x, nums))
# filter
evens = list(filter(lambda x: x%2==0, nums))
# reduce
total = reduce(lambda x, y: x+y, nums)
print(squares)
print(evens)
print(total)
# Output
# [1, 4, 9, 16, 25]
# [2, 4]
# 15
Important Points
- Lambda functions are anonymous functions.
- Best for short operations.
- Commonly used with
map(),filter(), andsorted(). - Avoid very complex lambda expressions for readability.
Key Takeaways
- Lambda functions are anonymous functions defined with
lambda arguments: expression - They can have any number of arguments but only one expression
- Lambda functions are inline - defined where they're used
- Common uses:
map(),filter(),reduce(),sorted(),min(),max() map(function, iterable): Apply function to all elementsfilter(function, iterable): Keep elements where function returns Truereduce(function, iterable): Cumulatively apply function (fromfunctools)- Use
keyparameter withsorted(),min(),max()for custom comparison - Lambda can create closures - functions that remember their enclosing scope
- Use list comprehensions as alternatives to
map()andfilter()for readability - Avoid complex logic in lambda - use regular functions for multi-line operations
- Lambda with
*argsand**kwargssupports variable arguments - Use
functools.partialfor partial function application (alternative to lambda) - Lambda functions are function objects - can be stored, passed as arguments, returned
- Performance: List comprehensions are often faster than
map()with lambda