When is del useful in Python? When is del useful in Python? python python

When is del useful in Python?

Firstly, you can del other things besides local variables

del list_item[4]del dictionary["alpha"]

Both of which should be clearly useful. Secondly, using del on a local variable makes the intent clearer. Compare:

del foo


foo = None

I know in the case of del foo that the intent is to remove the variable from scope. It's not clear that foo = None is doing that. If somebody just assigned foo = None I might think it was dead code. But I instantly know what somebody who codes del foo was trying to do.

There's this part of what del does (from the Python Language Reference):

Deletion of a name removes the binding of that name from the local or global namespace

Assigning None to a name does not remove the binding of the name from the namespace.

(I suppose there could be some debate about whether removing a name binding is actually useful, but that's another question.)

One place I've found del useful is cleaning up extraneous variables in for loops:

for x in some_list:  do(x)del x

Now you can be sure that x will be undefined if you use it outside the for loop.