logo
31

Lambda Expressions

⏱️ 20 min

Lambda: Lightweight Throwaway Functions

What You Might Be Wondering

"I already have def. Why do I need lambda?"

lambda doesn't replace def. It's a shorthand for tiny, one-off rules where writing a full function would be overkill.

One-Line Definition

lambda creates an anonymous function. Syntax: lambda parameters: expression.

Real-Life Analogy

def is a formal document. lambda is a sticky note. For quick throwaway rules, a sticky note is faster.

Minimal Working Example

add = lambda a, b: a + b
print(add(3, 5))  # 8

Most Common Use: Sort Key

students = [
    {"name": "Amy", "score": 88},
    {"name": "Bob", "score": 95},
    {"name": "Cara", "score": 91},
]

sorted_students = sorted(students, key=lambda s: s["score"], reverse=True)
print(sorted_students[0]["name"])  # Bob

Quick Quiz (3 min)

  1. Write lambda x: x * 2.
  2. Sort students by name ascending.
  3. Sort by score descending first, then by name ascending.

Quiz Rubric & Grading Criteria

  • Direction: write runnable code that covers the core requirements and edge cases from the prompt.
  • Criterion 1 (Correctness): main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.

Take-Home Task

Convert a small "formatting function" from def to lambda and explain whether it's actually more readable.

Acceptance Criteria

You can independently:

  • Write basic lambda expressions
  • Use lambda with sorting and higher-order functions
  • Judge where lambda ends and def should begin

Common Errors & Debugging Steps (Beginner Edition)

  • Error message looks like gibberish: read the last line for the error type (TypeError, NameError, etc.), then trace back to the offending line.
  • Not sure what a variable holds: drop a temporary print(variable, type(variable)) to check.
  • Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.

Common Misconceptions

  • Misconception: using lambda everywhere is more Pythonic.

  • Reality: for anything complex, def is easier to maintain and debug.

  • Misconception: lambda can have multiple statements.

  • Reality: lambda supports a single expression only. That's the hard limit.