C
Python/Intermediate/Lesson 10

Lambda Functions

30 min·theory
This chapter
2/8
Python

Lambda Functions

🎯 By the end of this lesson

After reading this lesson, you will be able to confidently do the following 3 things.

  • ✅ lambda + map / filter / sorted key argument
  • ✅ Extract a complex lambda into a named function
  • ✅ Fix arguments with functools.partial

Keep the learning goals as a checklist — close the lesson once you can answer all of them.

5 lambda patterns — code + output

lambda = an anonymous one-liner function. Use it when you need a short function right there on the spot.


1. def vs lambda — same function

python
# Regular function
def add(a, b):
    return a + b

# Same thing with lambda
add = lambda a, b: a + b

print(add(3, 5))      # 8

lambda parameters: expressionreturn is implicit.


2. Real use case — sorted() key

python
students = [
    ("Hong Gildong", 28, 85),
    ("Lee Mongryong", 30, 92),
    ("Seong Chunhyang", 25, 78),
]

# Sort by score (3rd element = index 2)
score_sorted = sorted(students, key=lambda x: x[2])
print(score_sorted)
# [('Seong Chunhyang', 25, 78), ('Hong Gildong', 28, 85), ('Lee Mongryong', 30, 92)]

# Sort by score descending
score_desc = sorted(students, key=lambda x: -x[2])

key=lambda x: ... is the most common use of lambda. A function used once and thrown away.


3. Combined with map and filter

python
numbers = [1, 2, 3, 4, 5]

# map — transformation
squares = list(map(lambda x: x * x, numbers))
print(squares)              # [1, 4, 9, 16, 25]

# filter — filtering
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)              # [2, 4]

⚠️ However, list comprehension is more Pythonic — [x*x for x in numbers].


4. dict sorting — by value

python
scores = {"Hong Gildong": 85, "Lee Mongryong": 92, "Seong Chunhyang": 78}

# Sort by value
sorted_scores = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
print(sorted_scores)
# [('Lee Mongryong', 92), ('Hong Gildong', 85), ('Seong Chunhyang', 78)]

5. Bad example — overusing lambda

python
# ❌ Do not use like this — a named function is clearer
value_validation = lambda x: isinstance(x, int) and x > 0 and x < 100

# ✅ Clearly with def
def value_validation(x):
    """Check if it's a positive integer between 1 and 99"""
    return isinstance(x, int) and 0 < x < 100

Rule: Use lambda only when you use it once, right there. If you need a name, use def.


One-line summary

Use caseExample
sorted keysorted(xs, key=lambda x: x[1])
mapmap(lambda x: x*2, xs)
filterfilter(lambda x: x>0, xs)
dict sortingsorted(d.items(), key=lambda kv: kv[1])

Key takeaway: A short, single-use function with no name. If it gets long, use def.

💻 Lambda function examples
# Basic lambda
add = lambda x, y: x + y
print(add(3, 5))  # 8

# Comparison with regular function
def add_func(x, y):
    return x + y

# Usage as sort key
students = [
    {'name': 'Cheolsu', 'score': 85},
    {'name': 'Younghee', 'score': 92},
    {'name': 'Minsu', 'score': 78}
]

# Sort by score
sorted_students = sorted(students, key=lambda x: x['score'])
print([s['name'] for s in sorted_students])  # ['Minsu', 'Cheolsu', 'Younghee']

# Reverse sort
sorted_desc = sorted(students, key=lambda x: x['score'], reverse=True)

# Sort list of tuples
pairs = [(1, 'b'), (2, 'a'), (3, 'c')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)  # [(2, 'a'), (1, 'b'), (3, 'c')]

# With conditional expression
check = lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero"
print(check(5))  # Positive

💡 Key points

1. Lambda supports only a single expression (statements are not allowed)
2. For complex logic, a regular function is recommended
3. Useful as the key argument in sorted(), max(), min()

Python is used across many domains thanks to its concise, readable syntax. As an interpreted language, it can be executed immediately in a REPL environment. Follow the PEP 8 coding style guide and use Black/autopep8 for automatic formatting. Type hints improve code readability and IDE support. Use pip for package management and venv/conda for virtual environments.

🐍 Try it yourself — Lambda Functions

Run the concepts above as actual code. The fastest way to learn is to change values and see how the behavior changes firsthand.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try asking AI like this

Knowing the concepts in this lesson lets you give specific instructions to AI. Instead of a vague 'fix this,' you make vocabulary-driven requests — and that's where token savings begin.

  • 'Add type hints + a docstring to this function'
  • 'Remove the side effects (global variable mutation) from this function and turn it into a pure function'

Why this reduces tokens

Without understanding the concepts, even after receiving an AI response you have to ask 'What does that mean?' again. That follow-up question is what eats your tokens. Learn the concept once and the conversation ends in one go.

Read this first: List Comprehension
Up next: Generators
Lambda Functions - Python