Course Progress38%
🍎 Python Basics Topic 38 / 100
⏳ 7 min read

Lambda Functions

Anonymous one-line functions — tiny functions you write inline, perfect for sorting, filtering, and short transformations.

"A lambda is a function so small it doesn't need a name. Use it once, inline, and move on."

— ShurAI

def vs lambda — Same Thing, Different Size

python
# Regular function — needs a name and return
def double(x):
    return x * 2

# Lambda — same thing in one line
double = lambda x: x * 2

print(double(5))    # 10 — identical result

Anatomy of a Lambda

lambda x, y : x + y
keyword
replaces def
parameters
(can have many)
expression
automatically returned

Multiple Parameters

python
add       = lambda a, b: a + b
full_name = lambda first, last: f"{first} {last}"
discount  = lambda price, pct: round(price * (1 - pct/100))

print(add(3, 4))                      # 7
print(full_name("Riya", "Sharma"))   # Riya Sharma
print(discount(500, 20))             # 400

Best Use: Sorting with key=

The most common real-world use of lambda is as the key argument in sorted(). It tells Python what to sort by:

python
students = [
    {"name": "Sneha",  "score": 92},
    {"name": "Arjun",  "score": 75},
    {"name": "Riya",   "score": 88},
]

# Sort by score (highest first)
by_score = sorted(students, key=lambda s: s["score"], reverse=True)
for s in by_score:
    print(f"{s['name']}: {s['score']}")

# Sort by name alphabetically
by_name = sorted(students, key=lambda s: s["name"])
for s in by_name:
    print(f"{s['name']}")
output
Sneha: 92
Riya: 88
Arjun: 75

Arjun
Riya
Sneha

Lambda with Tuples — Sort by Second Element

python
pairs = [("banana", 3), ("apple", 7), ("mango", 1)]

# Sort by the count (second item in each tuple)
sorted_pairs = sorted(pairs, key=lambda p: p[1])
print(sorted_pairs)
# [('mango', 1), ('banana', 3), ('apple', 7)]

When to Use Lambda vs def

✓ Use lambda when:
The function is very short (one expression).
You only need it in one place.
Passing it as key= to sorted or similar.
✓ Use def when:
The function needs multiple lines.
You reuse it in more than one place.
It needs a docstring or meaningful name.

"Lambda is not a replacement for def. It's a tool for short, throwaway functions that live in exactly one place."

— ShurAI

🧠 Quiz — Q1

What does lambda x: x * 3 do?

🧠 Quiz — Q2

What is the result of (lambda a, b: a + b)(4, 5)?

🧠 Quiz — Q3

In sorted(items, key=lambda x: x[1]), what does the lambda do?

🧠 Quiz — Q4

When should you use def instead of lambda?