Python - Lambda Functions

Overview

Estimated time: 15–25 minutes

Use lambda (anonymous) functions for small, throwaway callables and learn when a named def is better.

Learning Objectives

  • Create lambda functions and pass them to higher-order functions.
  • Use with sorted, map, filter, and custom APIs.
  • Prefer def when readability or reuse matters.

Prerequisites

Examples

nums = [5, 2, 9, 1]
print(sorted(nums, key=lambda x: -x))

words = ["apple", "banana", "pear"]
print(list(map(lambda w: w.upper(), words)))
print(list(filter(lambda w: len(w) > 4, words)))

Common Pitfalls

  • Writing complex lambdas: favor a named function for multi-step logic.
  • Overusing map/filter when comprehensions are clearer.

Checks for Understanding

  1. What is the typical use case for a lambda?
  2. When should you prefer def over lambda?
Show answers
  1. A short function as an argument to another function.
  2. When the logic is non-trivial or reused; readability first.

Exercises

  1. Sort a list of tuples by the second element using a lambda key.
  2. Use a lambda to transform a list of numbers into their squares.