Previous | Tutorial index | Next
Lambda functions (also called anonymous functions) are small, single‑expression functions that are defined without a name using the lambda keyword. They are typically used for short, throwaway operations where a full function definition would be unnecessarily verbose. Lambdas are a functional programming feature that allows you to write concise code, especially when working with higher‑order functions like map, filter, and sorted. However, they are limited to a single expression and cannot contain statements or multiple lines. In this tutorial, you will learn the syntax, typical use cases, and when to avoid them, as well as best practices for writing readable lambda expressions.
A lambda function is a small, anonymous function that can have any number of arguments but only one expression. It is defined using the lambda keyword. The result of the expression is automatically returned.
lambda arguments: expression
arguments – a comma‑separated list of parameters (just like a function definition).expression – a single expression that is evaluated and returned.# A lambda that squares a number
square = lambda x: x ** 2
print(square(5)) # 25
This is equivalent to:
def square(x):
return x ** 2
| Feature | Lambda Functions | Regular Functions (def) |
|---|---|---|
| Name | Anonymous (no identifier) | Named |
| Body | Single expression only | Multiple statements allowed |
| Return | Implicitly returns the expression result | Must use return explicitly |
| Statements | Cannot contain statements (e.g., if, for, while, print, raise) |
Can contain any statements |
| Type annotations | Not supported (but can be added via lambda with typing? Usually not) |
Supported |
| Documentation | No docstring | Can have docstring |
| Use cases | Short, inline, one‑off functions | Complex, reusable, documented logic |
Example of lambda with no statements:
# Valid
add = lambda a, b: a + b
# Invalid: lambda cannot contain if-else as a statement, but it can use conditional expression
# lambda x: if x > 0: return x else: return -x # SyntaxError
# But conditional expression works:
abs_value = lambda x: x if x >= 0 else -x
There are three common ways to invoke a lambda:
add = lambda x, y: x + y
result = add(3, 4) # 7
Wrap the lambda definition in parentheses and immediately pass arguments.
result = (lambda x, y: x + y)(3, 4) # 7
This is useful when you need a quick, one‑time computation.
This is the most common use case – passing lambdas to higher‑order functions like sorted, map, filter, and reduce.
The sorted() function and list.sort() accept a key function. Using a lambda allows you to sort by a specific attribute without defining a separate function.
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
# Sort by age (second element)
people_sorted = sorted(people, key=lambda person: person[1])
print(people_sorted) # [('Bob', 25), ('Alice', 30), ('Charlie', 35)]
map() to Apply a Function to Each Elementmap(function, iterable) applies the function to every element and returns an iterator.
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16]
filter() to Select Elementsfilter(function, iterable) keeps only elements for which the function returns True.
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6]
reduce() for Cumulative Operations (from functools)from functools import reduce
product = reduce(lambda a, b: a * b, [1, 2, 3, 4])
print(product) # 24
You can use a lambda to create a simple callback that passes additional arguments:
button = tk.Button(text="Click", command=lambda: print("Button clicked"))
Although lambdas cannot contain statements, they can use conditional expressions (ternary operator).
max_value = lambda a, b: a if a > b else b
print(max_value(10, 20)) # 20
if, for, while, print, raise, assert, etc.<lambda> instead of a clear function name.Rule of thumb: Use a lambda if the logic fits in a single line and the operation is obvious. Otherwise, define a regular function.
Like regular functions, lambdas are objects. You can store them in data structures, return them from functions, or use them as closures.
def make_multiplier(n):
return lambda x: x * n
times_3 = make_multiplier(3)
print(times_3(10)) # 30
def).def for anything beyond trivial operations – readability counts.sorted, map, filter – this is their primary niche.What is the correct syntax for a lambda that adds two numbers?
lambda a, b: a + blambda(a, b): a + bdef lambda(a, b): return a + blambda a, b -> a + bCan a lambda function contain multiple statements?
return explicitly.What does the following code output?
f = lambda x: x * 2
print(f(3))
639NoneHow do you call a lambda immediately without assigning it to a variable?
lambda x: x+1(5)(lambda x: x+1)(5)lambda (5) x: x+1call(lambda x: x+1, 5)True or False: Lambda functions can have a docstring.
Which of the following is a valid use of a lambda with map?
map(lambda x: x**2, [1,2,3])map(lambda x: return x**2, [1,2,3])map(lambda x: x**2; return x, [1,2,3])map(x: x**2, [1,2,3])Given numbers = [1, 2, 3, 4], which code filters out odd numbers?
filter(lambda x: x % 2 == 0, numbers)filter(lambda x: x % 2 != 0, numbers)filter(lambda x: x % 2, numbers)filter(lambda x: x, numbers)What is the main advantage of using a lambda over a named function for simple operations?
Which of the following is NOT a valid lambda expression?
lambda x, y: x + ylambda x: x ** 2 if x > 0 else -xlambda x: for i in range(x): passlambda x: x * 2 + 1What is the result of (lambda x, y: x if x > y else y)(5, 3)?
53True8Exercise 1: Basic Lambda
Write a lambda that computes the cube of a number. Assign it to a variable cube and test with 5.
Exercise 2: Sort by Length
Given words = ["apple", "kiwi", "banana", "pear"], use sorted() with a lambda to sort the list by string length (shortest first).
Exercise 3: Filter Strings with 'e'
Given fruits = ["apple", "banana", "cherry", "date", "elderberry"], use filter() with a lambda to get only fruits that contain the letter 'e'.
Exercise 4: Map to Square
Using map and a lambda, produce a list of squares of numbers from 0 to 9.
Exercise 5: Conditional Lambda
Write a lambda that takes two numbers and returns the larger one using a conditional expression. Assign it to max_of_two and test.
1. Sorting by Multiple Criteria
Given employees = [("Alice", "Engineering", 75000), ("Bob", "Sales", 60000), ("Charlie", "Engineering", 80000), ("Diana", "Sales", 65000)], sort by department (ascending) and then by salary (descending) within each department using a lambda key.
2. Custom Reduce
Write a function my_reduce(iterable, func) that mimics reduce() using a loop. Test it with a lambda that multiplies numbers.
print(my_reduce([2,3,4], lambda x,y: x*y)) # 24
</details>
**3. Data Transformation with Lambdas**
Given `students = {"Alice": [85, 92, 78], "Bob": [70, 65, 80], "Charlie": [90, 88, 95]}`, produce a new dictionary with average scores using a lambda.
<details><summary>Sample Answer</summary>
```python
students = {"Alice": [85, 92, 78], "Bob": [70, 65, 80], "Charlie": [90, 88, 95]}
averages = {name: sum(scores)/len(scores) for name, scores in students.items()}
print(averages)
4. Lambda as Default Argument
Write a function make_adder(n) that returns a lambda that adds n. Use it to create add5 and add10.
add5 = make_adder(5) add10 = make_adder(10) print(add5(10)) # 15 print(add10(10)) # 20
</details>
**5. Chaining Lambdas**
Define a lambda that takes a number and returns a lambda that multiplies by that number. Create a pipeline that squares a number then doubles it.
<details><summary>Sample Answer</summary>
```python
multiply_by = lambda factor: lambda x: x * factor
double = multiply_by(2)
square = lambda x: x * x
pipeline = lambda x: double(square(x))
print(pipeline(3)) # 18
key=lambda emp: (emp[1], -emp[2]) for descending salary.{name: sum(scores)/len(scores) for name, scores in students.items()} or use map.def make_adder(n): return lambda x: x + n.multiply_by = lambda factor: lambda x: x * factor; then double = multiply_by(2). For composition, use lambda x: double(square(x)).In this tutorial, you have learned:
lambda arguments: expression.def functions.sorted, map, filter, and reduce.Lambdas are a powerful tool for concise functional programming in Python. When used appropriately, they can make your code more expressive and compact. However, they are not a replacement for regular functions and should be used sparingly when clarity is paramount.
Next Steps: In Tutorial 7, we will explore Higher‑Order Functions in detail, including map, filter, reduce, and the functools and itertools modules.
Happy lambdas!