Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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.

Intermediate40 min

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(), and filter()
  • 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.

Normal def add versus lambda add = lambda a, b: a + b

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.

variable = lambda parameters : expression — no return keyword
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:

python
def add(a, b):
    return a + b

Lambda — one line, implicit return:

python
add = lambda a, b: a + b

Both behave the same:

python
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:

code
30
30
<class 'function'> <class 'function'>

Both are objects of type function.


Example 1 — Sum of two numbers

python
add = lambda a, b: a + b
print(add(10, 20))
10, 20 into lambda a+b then 30

Example 2 — Square of a number

python
square = lambda x: x ** 2
print(square(7))

Output: 49

Formula: x → x²


Example 3 — Maximum of two numbers

Lambda supports conditional expressions.

python
find_max = lambda a, b: a if a > b else b
print(find_max(15, 9))
If a greater than b return a else return b

Example 4 — Even or odd

python
is_even = lambda n: "Even" if n % 2 == 0 else "Odd"
print(is_even(12))
print(is_even(7))

Output:

code
Even
Odd

Lambda can return strings, not just numbers.


Example 5 — Sum and average of a list

python
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))
List of 10, 20, 30, 40 through lambda sum and len to 25.0

Example 6 — Lambda with sorted()

This is the most common real-world use.

python
students = [
    ("Alice", 88),
    ("Bob", 95),
    ("Carol", 72),
]

print(sorted(students, key=lambda s: s[1]))
lambda key extracts the marks 88, 95, 72 for sorting

The lambda tells Python: use the second element as the sorting key.

python
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:

python
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.

python
employees = [
    ("Alice", 50000),
    ("Bob", 75000),
]

updated = list(map(lambda e: (e[0], e[1] * 1.3), employees))
print(updated)
Input Alice 50000 through map *1.30 to Alice 65000

Output:

code
[('Alice', 65000.0), ('Bob', 97500.0)]

map() applies the lambda to every item.


Example 9 — String processing

python
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:

python
result = (lambda a, b: a * a + b * b)(3, 4)
print(result)
lambda a²+b² called with (3,4) result 25

Useful for one-off calculations.


Lambda with filter()

filter() keeps only matching values.

python
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda n: n % 2 == 0, nums))
print(evens)
1 2 3 4 5 6 through filter even to 2 4 6

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:

python
words = ["python", "ai", "lambda"]
words.sort(key=lambda w: len(w))
print(words)

Bad lambda — hard to read:

python
process = lambda x: x if x > 0 else (x * 2 if x > -10 else x ** 2)
# Use def instead

Common mistakes

Multiple statements — not allowed:

python
# lambda x:
#     print(x)
#     return x

Lambda allows only one expression.

Using return — illegal inside lambda:

python
# lambda x: return x    # SyntaxError

Complex 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:

python
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:

code
[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:

  1. Change square(7) to square(12) — expect 144.
  2. Sort students by name: key=lambda s: s[0].
  3. Change the hike from 1.3 to 1.5 and confirm Alice becomes 75000.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