A closure is a function that remembers the variables from the scope it was created in, even after that outer scope has already finished running. This happens naturally whenever an inner function, defined inside another function, uses a variable from that enclosing function and is then returned or passed elsewhere to be called later.
#how it works
1
Define an outer function with a local variable
This variable will be the one the closure remembers.
2
Define an inner function using that variable
Nested inside the outer function’s body.
3
Return the inner function itself
Not the result of calling it — the function object itself.
4
Access continues after the outer function ends
The returned inner function still reaches that specific enclosing variable.
5
Each call creates its own independent closure
Remembering its own separate copy of that variable.
#example
def make_multiplier(factor):
def multiply(number):
return number * factor
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5))
print(triple(5))
Output
10
15
1make_multiplier(2) runs, creates the inner multiply function, and returns it — but that inner function still remembers factor as 2, even after make_multiplier has already finished.
2double(5) calls that remembered version, computing 5 * 2.
3make_multiplier(3) creates a completely separate closure, remembering its own factor as 3, independent of the first one.
4triple(5) uses that separate remembered value, computing 5 * 3 — proving each closure keeps its own private copy of the enclosing variable.
#use cases
Creating specialized functions from a general one, like make_multiplier building double and triple from the same underlying logic
Implementing simple, private state for a function without a full class, since the enclosing variable acts like hidden data
Understanding how decorators actually work internally, since they rely on this same closure mechanism
Building callback functions that need to remember some specific context from where they were created
Practice Python interview questions
Every Python lesson maps to the matching interview topic, with answers written for current Python versions.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses →Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free →Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books →