when does python delete variables?

Implementations use reference counting to determine when a variable should be deleted.

After the variable goes out of scope (as in your example) if there are no remaining references to it, then the memory will be freed.

def a():
    x = 5 # x is within scope while the function is being executed
    print x

a()
# x is now out of scope, has no references and can now be deleted

Aside from dictionary keys and elements in lists, there's usually very little reason to manually delete variables in Python.

Though, as said in the answers to this question, using del can be useful to show intent.


It's important to keep two concepts separate: names and values. A variable in Python is a name referring to a value. Names have scope: when you define a local variable (by assigning a value to a name), the variable's scope is the current function. When the function returns, the variable goes away. But that doesn't mean the value goes away.

Values have no scope: they stick around until there are no more names referring to them. You can create a value in a function, and return it from that function, making a name outside the function refer to the value, and the value won't be reclaimed until some future point when all the references to it have gone away.

More detail (including pictures!) is here: Facts and Myths about Python Names and Values.