6.9 Lifetime of Variables
When a Python variable's lifetime begins and ends, how the del statement differs from letting a scope exit naturally, and how lifetime connects to garbage collection.
Creation
A variable’s lifetime begins the moment it’s first assigned a value.
Usage
A variable remains usable for as long as its scope is active (see 6.8 Variable Scope) and it hasn’t been deleted.
Deletion
A variable’s lifetime ends when its scope exits — a function returns, for instance — or it’s explicitly removed with del.
The del Statement
What Is It?
Explicitly removes a name’s binding, immediately. If that was the object’s last reference, it becomes eligible for garbage collection right away (see 6.6 Garbage Collection).
>>> y = [1, 2, 3]
>>> del y
>>> y
Traceback (most recent call last):
NameError: name 'y' is not defined
How Is It Used?
del removes the name, not necessarily the object — if another variable still references the same object, that object stays alive:
>>> a = [1, 2, 3]
>>> b = a
>>> del a
>>> b # the object is still alive -- b still references it
[1, 2, 3]
Quick Interview Answer
“A variable’s lifetime runs from its first assignment until its scope exits or it’s explicitly removed with
del.delonly removes that one name’s binding, immediately — it doesn’t necessarily destroy the underlying object, which stays alive as long as any other reference to it exists. The object itself is only freed once its reference count reaches zero, which is a separate concern covered by garbage collection.”
Common Mistakes
- Assuming
del xdestroys the objectxreferenced — it only removes that one name’s binding; the object survives if anything else still references it. - Relying on a function-local variable’s value surviving after the function returns — its lifetime ends with the function call unless the value was explicitly returned.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form