Thuta Learning
Python
AdvancedProgrammingBeginner

Lambdas, Closures & functools

PythonLesson 6130 min

What you'll walk away with

  • Explain that a lambda remembers enclosing variables by name and reads them only when it is called
  • Fix the late-binding bug in a loop with a default argument, partial or a factory function
  • Build new functions with some arguments pre-filled using functools.partial
  • Use operator.itemgetter, attrgetter, methodcaller and reduce in place of lambdas
  • Compose small functions into one pipeline

Explain it simply

Explain it simply

Imagine leaving a note that says "bring the shirt from the wardrobe". The note is not a photo of a particular shirt; it only points at a place. What your friend brings depends on what is in the wardrobe when they read the note, so if someone swapped the shirt after you left, they bring the new one.

Outside variables inside a lambda work like that note. lambda x: x + i does not record the value of i when it is created; it looks i up when it is called. Once you understand this, you can use lambdas safely and see why tools such as partial and the operator module are so useful.

Problem → Why → Solution

The problem: three buttons that all report the last name

Say you build one click handler per menu item by creating lambdas in a loop. The code looks right and raises no error. Yet whichever button you press, it reports "Quit" rather than its own label. A test that checks only one handler might never reveal the bug.

menu.py
labels = ["Save", "Open", "Quit"]
handlers = []
for label in labels:
    handlers.append(lambda: f"clicked {label}")

print(handlers[0]())   # clicked Quit   (expected: clicked Save)
print(handlers[1]())   # clicked Quit   (expected: clicked Open)

Why does every handler say Quit?

All three lambdas refer by name to the same variable, label. By the time the handlers are called the loop has finished and label holds its final value, "Quit", so every lambda reads that. This is called late binding, and the fix is to bind the value at creation time.

Core concept: a lambda captures variables, not values

When a lambda created inside a function uses a variable of that outer function, you get a closure. make_multiplier(3) returns lambda x: x * factor, and the lambda can still read factor after make_multiplier has finished. Python keeps that variable in a small box called a cell, and the lambda holds the box, not the value. Each call to make_multiplier creates a new scope with a new cell, so triple and double do not share a factor.

The trouble starts in loops. A for loop does not create a new scope; it reuses one variable i and stores a new value in it on each pass. So all three lambdas in [lambda x: x + i for i in range(3)] hold the same cell, i is 2 by the time they are called, and every one computes x + 2. A list comprehension does have its own scope, but all its iterations share that one scope, so the result is the same.

There are three fixes. First, use a default argument such as lambda x, i=i: x + i; defaults are evaluated once, when the lambda is created, so they store that moment's value. Second, call a factory function like make_adder(i) so each call gets a fresh scope. Third, use functools.partial(add, i), which stores its arguments at creation time.

functools.partial(func, *args, **kwargs) returns a new callable with some of func's arguments already filled in. partial(int, base=2) becomes a function that parses binary strings. The operator module provides Python's operators as functions: operator.mul does the same job as lambda a, b: a * b, and itemgetter(2, 0) builds a function that pulls out indexes 2 and 0 as a tuple. These are named, so they read clearly, their repr shows what they do, and they have no late-binding issue.

Mental model: a lambda holding a box
  1. Creating a lambda grabs the cell
  2. The loop keeps changing the cell
  3. Calling it reads the cell now
  4. i=i or partial freezes the value

Defaults and partial evaluate at creation time; a lambda body evaluates at call time.

General pattern

python
funcs = [lambda x, v=v: op(x, v) for v in values]   # bind v now

from functools import partial, reduce
specialised = partial(func, fixed_arg, keyword=fixed_value)

import operator
key = operator.itemgetter("field")            # lambda item: item["field"]
total = reduce(operator.add, items, start)

compose = lambda *fs: reduce(lambda f, g: lambda x: g(f(x)), fs)

The first line binds the value with a default argument inside a loop. partial pre-fills arguments and the operator functions replace tiny lambdas. The last line is the shape of a compose that chains functions left to right.

Example: closures, late binding, partial, operator and compose

Sections 2 and 3 differ only in how the lambdas are built, yet their results differ completely. Sections 5 and 6 replace lambdas with operator functions, and section 7 joins three functions into a single pipeline.

functional_tools.py
import operator
from functools import partial, reduce


# 1. A lambda returned from a function closes over that call's variables
def make_multiplier(factor):
    return lambda x: x * factor

triple = make_multiplier(3)
print("1. closure:", triple(7))

# 2. Late binding: every lambda reads i when it RUNS, after the loop ended
adders = [lambda x: x + i for i in range(3)]
print("2. late binding:", [add(10) for add in adders])

# 3. Fix: a default argument is evaluated once, when each lambda is created
adders = [lambda x, i=i: x + i for i in range(3)]
print("3. default-arg fix:", [add(10) for add in adders])

# 4. functools.partial freezes some arguments of an existing function
parse_binary = partial(int, base=2)
print("4. partial:", parse_binary("1011"), parse_binary("111"))

# 5. operator functions replace one-line lambdas
rows = [("Sai", 25, 88), ("Aye", 20, 95), ("Mya", 30, 88)]
print("5. itemgetter:", sorted(rows, key=operator.itemgetter(2, 0)))
print("6. reduce + mul:", reduce(operator.mul, [1, 2, 3, 4], 1))


# 7. Composition: chain small functions into one, left to right
def compose(*funcs):
    return reduce(lambda f, g: lambda x: g(f(x)), funcs, lambda x: x)

slugify = compose(str.strip, str.lower, operator.methodcaller("replace", " ", "-"))
print("7. compose:", slugify("  Learn Python Fast "))

Code breakdown

  1. Line 6-10return lambda x: x * factor

    Every call to make_multiplier(3) creates a new scope with factor = 3, and the lambda holds that scope's cell. Nothing ever changes that cell, so triple(7) reliably gives 21.

  2. Line 13-14adders = [lambda x: x + i for i in range(3)]

    All three lambdas share the comprehension's single i. When add(10) runs, i already holds its last value, 2, so the result is [12, 12, 12], not [10, 11, 12].

  3. Line 17-18adders = [lambda x, i=i: x + i for i in range(3)]

    The right-hand i in i=i is evaluated when each lambda is created and stored as the default of the lambda's own parameter i. Each lambda therefore remembers 0, 1 and 2 separately.

  4. Line 21-22parse_binary = partial(int, base=2)

    partial returns a callable with base=2 already supplied to int, so parse_binary("1011") is int("1011", base=2), which is 11. No new def or lambda is needed.

  5. Line 26sorted(rows, key=operator.itemgetter(2, 0))

    itemgetter(2, 0) returns a (score, name) tuple for each row, just like lambda r: (r[2], r[0]). Mya and Sai tie on 88, so the name decides and Mya comes first.

  6. Line 31-35return reduce(lambda f, g: lambda x: g(f(x)), funcs, lambda x: x)

    reduce starts from the identity function and wraps one function at a time, producing a single function that runs strip, then lower, then replace. These lambdas have no late-binding problem, because each call of the outer lambda by reduce gets a fresh scope for f and g.

You should see
1. closure: 21
2. late binding: [12, 12, 12]
3. default-arg fix: [10, 11, 12]
4. partial: 11 7
5. itemgetter: [('Mya', 30, 88), ('Sai', 25, 88), ('Aye', 20, 95)]
6. reduce + mul: 24
7. compose: learn-python-fast

The operator functions you will use most

operator functionEquivalent lambda
itemgetter("name")lambda d: d["name"]
itemgetter(1, 0)lambda t: (t[1], t[0])
attrgetter("owner.city")lambda o: o.owner.city
methodcaller("split", ",")lambda s: s.split(",")
add, mul, truedivlambda a, b: a + b (and so on)

attrgetter also accepts a dotted path, so it can read an attribute of an object nested inside another object. These functions are implemented in C and are often slightly faster than a lambda when sorting millions of items, but their main benefit is readability. If speed matters, measure it on your own data with timeit.

attrgetter_demo.py
from dataclasses import dataclass
from operator import attrgetter, methodcaller


@dataclass
class Owner:
    city: str


@dataclass
class Shop:
    name: str
    owner: Owner


shops = [Shop("Tea", Owner("Yangon")), Shop("Books", Owner("Bago"))]
print([s.name for s in sorted(shops, key=attrgetter("owner.city"))])
print(list(map(methodcaller("split", ","), ["a,b", "c"])))

In real projects

Where this shows up in real projects

The late-binding bug appears most often in GUI and event code. In Tkinter, writing for name in files: Button(..., command=lambda: open_file(name)) makes every button open the last file. The same problem can surface wherever a loop builds callbacks: web scrapers, retry schedulers, test parametrisation. Writing command=partial(open_file, name) is usually the cleanest fix.

partial is used widely to pre-fill configuration: wrapping json.dumps as partial(json.dumps, indent=2, ensure_ascii=False), passing a worker with extra arguments to executor.map, or adapting a function to a required callback signature. operator.itemgetter and attrgetter turn up in reporting code and in sorting ORM results, while the compose pattern helps build text-cleaning pipelines and data-validation steps out of small functions. Being able to test each small function on its own is a benefit too.

Common mistakes

Common mistakes

1. Using the loop variable directly inside a lambda

Every function in [lambda: n * n for n in range(3)] returns 4. Nothing raises an error, so a test that checks only the last item can still pass. Whenever you build callbacks in a loop, bind the value with an n=n default, partial or a factory function.

2. Letting callers override the default-argument fix

In lambda x, i=i: x + i, i becomes a real parameter, so a caller who writes f(10, 99) silently replaces the bound value. For callbacks you expose as part of an API, partial or a factory function keeps the signature clean.

3. Pre-filling the wrong positional argument with partial

partial fills positional arguments from the left. To bind the rate of apply_discount(price, rate), writing partial(apply_discount, 0.2) makes 0.2 the price and gives wrong results. Bind any argument that is not the leftmost one by keyword: partial(apply_discount, rate=0.2).

4. Calling reduce without a start value

reduce(operator.add, []) raises TypeError: "reduce() of empty iterable with no initial value". If the data can be empty, pass a third argument, as in reduce(operator.add, items, 0). For plain sums and products, sum() and math.prod() are clearer anyway.

Mini challenge

Mini challenge: discount and order tools

Build small tools for an online shop with partial, operator and compose, using as few lambdas as possible. Avoid late binding when you create discount functions in a loop.

  • Create 10%, 20% and 30% discount functions with partial inside one loop
  • Sort orders with operator.itemgetter by total, highest first, larger id first on ties
  • Extract the customer names with map() and itemgetter
  • Compose 20% discount, then 5% tax, then rounding to 2 decimals into one pipeline
shop_tools.py
import operator
from functools import partial, reduce


def apply_discount(price, rate):
    return round(price * (1 - rate), 2)


def compose(*funcs):
    # TODO: chain funcs left to right with reduce (start from an identity function)
    ...


discounts = ...   # TODO: one partial per rate in (0.1, 0.2, 0.3), bound by keyword
# TODO: print each discount applied to 50

orders = [
    {"id": 3, "customer": "Mya", "total": 120.0},
    {"id": 1, "customer": "Aye", "total": 75.5},
    {"id": 2, "customer": "Sai", "total": 120.0},
]
# TODO: sort with itemgetter("total", "id") in reverse, print the ids
# TODO: print the customer names using map() and itemgetter
# TODO: build final_price with compose and partial, print final_price(50)

Expected: discounts on 50: [45.0, 40.0, 35.0] ranked ids: [3, 2, 1] customers: ['Mya', 'Aye', 'Sai'] final price for 50: 42.0

Show hint

For the tax, partial(operator.mul, 1.05) is a function that multiplies its input by 1.05. round can be wrapped as partial(round, ndigits=2). The identity function is lambda x: x.

Show solution
shop_tools.py
import operator
from functools import partial, reduce


def apply_discount(price, rate):
    return round(price * (1 - rate), 2)


def compose(*funcs):
    return reduce(lambda f, g: lambda x: g(f(x)), funcs, lambda x: x)


# Discount functions built in a loop: partial binds rate immediately
discounts = [partial(apply_discount, rate=r) for r in (0.1, 0.2, 0.3)]
print("discounts on 50:", [d(50) for d in discounts])

orders = [
    {"id": 3, "customer": "Mya", "total": 120.0},
    {"id": 1, "customer": "Aye", "total": 75.5},
    {"id": 2, "customer": "Sai", "total": 120.0},
]
ranked = sorted(orders, key=operator.itemgetter("total", "id"), reverse=True)
print("ranked ids:", [o["id"] for o in ranked])

customers = map(operator.itemgetter("customer"), orders)
print("customers:", list(customers))

add_tax = partial(operator.mul, 1.05)
to_cents = partial(round, ndigits=2)
final_price = compose(partial(apply_discount, rate=0.2), add_tax, to_cents)
print("final price for 50:", final_price(50))

Quick quiz 1 / 3

After fs = [lambda: k for k in "abc"], what does print([f() for f in fs]) show?

Quick quiz 2 / 3

Given def power(base, exp): return base ** exp and square = partial(power, exp=2), what is square(5)?

Quick quiz 3 / 3

Which key does the same job as lambda row: (row["city"], row["age"])?

What to remember

  • A lambda holds outside variables through cells, not values, and reads them when it is called.
  • Lambdas built in a loop all see the final value; bind it with an i=i default, partial or a factory function.
  • functools.partial pre-fills arguments; bind any argument that is not leftmost by keyword.
  • itemgetter, attrgetter, methodcaller and operator.add/mul replace tiny lambdas with readable named functions.
  • Composing with reduce chains small functions into a single pipeline.

Python Documentation — Functional Programming HOWTO — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Lambdas, Closures & functools | Thuta Learning