Lesson 06
Python Lambda Functions — Anonymous Functions Explained with Examples
Learn how Python lambda functions work, when to use them instead of def, and how they pair with sorted(), map(), and filter() in real apps.
What you will learn
- Lambda syntax vs a normal
def - Why a lambda has one expression and an implicit return
- Using lambda with
sorted(),map(), andfilter() - When to choose lambda vs a named function
- Common lambda mistakes to avoid
The big idea
A lambda is a function without a formal name. Instead of a full def, you write a single expression.
This continues from The return Statement.
A lambda function is an anonymous function that contains one expression and returns its result automatically.
Lambda syntax
The syntax is much shorter than def.
| Part | Meaning |
|---|---|
lambda |
Starts the anonymous function |
parameters |
Input variables |
: |
Separates input from logic |
expression |
Automatically returned |
Important: Lambda has implicit return. You never write return.
Lambda vs normal function
Normal function — multiple lines, explicit return:
def add(a, b):
return a + bLambda — one line, implicit return:
add = lambda a, b: a + bBoth behave the same:
def sumop(a, b):
return a + b
addop = lambda a, b: a + b
print(sumop(10, 20))
print(addop(10, 20))
print(type(sumop), type(addop))Output:
30
30
<class 'function'> <class 'function'>Both are objects of type function.
Example 1 — Sum of two numbers
add = lambda a, b: a + b
print(add(10, 20))Example 2 — Square of a number
square = lambda x: x ** 2
print(square(7))Output: 49
Formula: x → x²
Example 3 — Maximum of two numbers
Lambda supports conditional expressions.
find_max = lambda a, b: a if a > b else b
print(find_max(15, 9))Example 4 — Even or odd
is_even = lambda n: "Even" if n % 2 == 0 else "Odd"
print(is_even(12))
print(is_even(7))Output:
Even
OddLambda can return strings, not just numbers.
Example 5 — Sum and average of a list
find_sum = lambda lst: sum(lst)
find_avg = lambda lst: sum(lst) / len(lst)
nums = [10, 20, 30, 40]
print(find_sum(nums))
print(find_avg(nums))Example 6 — Lambda with sorted()
This is the most common real-world use.
students = [
("Alice", 88),
("Bob", 95),
("Carol", 72),
]
print(sorted(students, key=lambda s: s[1]))The lambda tells Python: use the second element as the sorting key.
print(sorted(students, key=lambda s: s[1], reverse=True))
print(sorted(students, key=lambda s: s[0]))Example 7 — Arithmetic toolkit
Tiny functions instead of one big calculator:
add = lambda a, b: a + b
sub = lambda a, b: a - b
mul = lambda a, b: a * b
power = lambda a, b: a ** b
print(add(5, 3))
print(sub(5, 3))
print(mul(5, 3))
print(power(2, 10))| Lambda | Example |
|---|---|
| Add | add(5, 3) = 8 |
| Subtract | sub(5, 3) = 2 |
| Multiply | mul(5, 3) = 15 |
| Power | power(2, 10) = 1024 |
Example 8 — map() with lambda
Every employee gets a 30% hike.
employees = [
("Alice", 50000),
("Bob", 75000),
]
updated = list(map(lambda e: (e[0], e[1] * 1.3), employees))
print(updated)Output:
[('Alice', 65000.0), ('Bob', 97500.0)]map() applies the lambda to every item.
Example 9 — String processing
reverse = lambda s: s[::-1]
title = lambda s: s.title()
palindrome = lambda s: s == s[::-1]
print(reverse("Python"))
print(title("hello world"))
print(palindrome("madam"))| Input | Output |
|---|---|
| Python | nohtyP |
| hello world | Hello World |
| madam | True |
Example 10 — Immediately invoked lambda
Define and execute in one expression:
result = (lambda a, b: a * a + b * b)(3, 4)
print(result)Useful for one-off calculations.
Lambda with filter()
filter() keeps only matching values.
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda n: n % 2 == 0, nums))
print(evens)Think of filter() as a sieve. The next lesson covers filter(), map(), and reduce() in depth.
When to use lambda vs def
This matters more than memorizing syntax.
| Use lambda | Use def |
|---|---|
| One expression | Multiple statements |
| Sort keys | Business logic |
map() / filter() |
Loops and conditions |
| Small callbacks | Reusable functions |
| Inline operations | Documentation needed |
Good lambda — short, readable, used once:
words = ["python", "ai", "lambda"]
words.sort(key=lambda w: len(w))
print(words)Bad lambda — hard to read:
process = lambda x: x if x > 0 else (x * 2 if x > -10 else x ** 2)
# Use def insteadCommon mistakes
Multiple statements — not allowed:
# lambda x:
# print(x)
# return xLambda allows only one expression.
Using return — illegal inside lambda:
# lambda x: return x # SyntaxErrorComplex business logic — use def for readability.
Interview cheat sheet
| Question | Answer |
|---|---|
| What is lambda? | Anonymous function |
return needed? |
No — implicit |
| Number of expressions | One |
| Can lambda have loops? | No |
| Best use | Inline operations |
| Used with | sorted, map, filter |
| Type | <class 'function'> |
Mini challenge
Predict the output without running it:
nums = [5, 2, 9, 1]
result = sorted(nums, key=lambda x: -x)
print(result)- The lambda returns the negative of each number
sorted()orders by those negative values- That produces descending order
Expected output:
[9, 5, 2, 1]If you understand syntax, implicit return, conditional lambdas, sorted(), map(), and filter(), you have mastered Python lambda functions.
Practice in the playground
The playground at the bottom already runs the examples above. Try:
- Change
square(7)tosquare(12)— expect144. - Sort students by name:
key=lambda s: s[0]. - Change the hike from
1.3to1.5and confirm Alice becomes75000.0.
Next: Special Functions — filter(), map(), and reduce().
For the full callback lab (named vs inline lambda, zip, two-iterable map(), and the salary-band pipeline), continue in Lambda and Special Functions.
Loading playground…
Check your understanding
Lambda functions quiz
What is another name for anonymous functions in Python?
1 / 10