Why does del cause a NameError instead of clearing my list in Python?
12:35 15 Mar 2026

I am relatively new to Python and am trying to understand the lifecycle of variables and memory management. I have a list containing several strings, and my goal was to "reset" or clear the list so that it no longer contains those items.

I attempted to use the del keyword as shown in the snippet below:

mylist = ['a', 'b', 'c']
del mylist
print(mylist)

However, when I run this code, the print statement fails and throws a NameError: name 'mylist' is not defined.

I expected the list to simply be empty (like []), but it seems the variable itself has been completely removed from the namespace. I have a few specific questions regarding this behavior:

  1. Scope and Namespace: Does del specifically target the object in memory, or does it only remove the reference (the name) from the local namespace?

  2. Memory Management: If I had other variables pointing to this same list (e.g., alias = mylist), would del mylist also affect the alias variable, or would the list persist in memory?

  3. Best Practices: If I want to keep the variable name active but remove all its contents to reuse it later in my script, what is the most "Pythonic" way to do that? Should I use mylist.clear(), assign it to an empty list mylist = [], or use slice assignment mylist[:] = []?

I am looking to understand the technical difference between deleting a reference and clearing an object's contents. Any insight into how Python handles these operations under the hood would be greatly appreciated.

python