Python’s del statement will allow you to remove names and references from different namespaces. It’ll also allow you to delete unneeded items from your lists and keys from your dictionaries. If you want to learn how to use del in your Python code, then this tutorial is for you. The del statement empowers you to better manage memory resources in your code, making your programs more efficient.
In this tutorial, you’ll learn how to:
- Write and use
delstatements in Python - Take advantage of
delto remove names from different scopes - Use
delfor removing list items and dictionary keys - Remove object attributes using
del - Write classes that prevent attribute deletion using
del
To get the most out of this tutorial, you should be familiar with Python’s built-in data types, specifically lists and dictionaries. You should also know the basics of classes and object-oriented programming in Python.
Free Bonus: Click here to download sample code that’ll empower you to write more efficient programs with Python’s del statement.
Getting to Know Python’s del Statement
Python’s del statement allows you to remove references to objects from a given namespace or container type. It performs an operation that’s the opposite of what an assignment statement does. It’s sort of an unassignment statement that allows you to unbind one or more names from their referenced objects.
This is a natural feature to have in Python. If you can create a variable by writing variable = value, then you must have the option to undo this operation by deleting variable. That’s where del comes on the scene.
The del statement can come in handy in different coding situations, such as:
- Freeing up memory resources
- Preventing accidental use of variables and names
- Avoiding naming conflicts
Of course, this list is incomplete. You may find some other appropriate use cases for this statement. In this tutorial, you’ll learn how the del statement works and how to use it in your code. To kick things off, you’ll start by learning the general syntax of del in Python.
Learning the del Syntax
A Python del statement consists of the del keyword, followed by a comma-separated series of references.
Note: In this tutorial, you’ll use the term reference to generically designate names or identifiers that can hold references to objects in Python.
Here’s the general syntax of the del statement in Python:
del reference_1[, reference_2, ..., reference_n]
The del statement allows you to remove one or more references from a given namespace. It also lets you delete data from mutable container types, such as lists and dictionaries.
You’ll often use this statement with a single argument. However, it also supports a series of arguments separated by commas.
In the above construct, reference_* represents any kind of identifier that can hold references to concrete objects stored in memory. In practice, these references can include:
- Identifiers, such as variables and names of functions, classes, modules, and packages
- Indices of mutable sequences, such as
a_list[index] - Slices of mutable sequences, like
a_list[start:stop:step] - Keys of dictionaries, like
a_dict[key] - Members of classes and objects, such as attributes and methods
You can use any of these references as arguments to del. If you use a comma-separated series of arguments, then keep in mind that del operates on every argument sequentially from left to right. This behavior can be risky when you’re removing items from lists, as you’ll learn later in this tutorial.
Here’s a quick example of using del to remove a variable:
>>> greeting = "Hi, Pythonista!"
>>> greeting
'Hi, Pythonista!'
>>> del greeting
>>> greeting
Traceback (most recent call last):
...
NameError: name 'greeting' is not defined
Once you’ve run the del statement, the variable greeting is no longer available. If you try to access greeting, then you get a NameError because that variable doesn’t exist anymore.
Removing reference holders like variables is the primary goal of del. This statement doesn’t remove objects. In the following section, you’ll dive deeper into the actual and immediate effects of running a del statement.
Understanding the Effects of del
As you’ve learned, Python’s del statement deletes references from namespaces or data containers. It doesn’t remove concrete objects. For example, you can’t remove literals of built-in types using del:
>>> del 314
File "<input>", line 1
del 314
^^
SyntaxError: cannot delete literal
>>> del "Hello, World!"
File "<input>", line 1
del "Hello, World!"
^^^^^^^^^^^^^^^
SyntaxError: cannot delete literal
In these examples, note that you can’t use the del statement directly on objects. You must use it with variables, names, and other identifiers, as you already learned:
>>> number = 314
>>> del number
However, running del like in this example doesn’t mean that you’re removing the number 314 from memory. It only removes the name number from your current namespace or scope.
When you pass an identifier—like a variable, class, function, or method name—as an argument to del, the statement unbinds the identifier from the referenced object and removes the identifier from its containing namespace. However, the referenced object may not be deleted from your computer’s memory immediately.
Similarly, when you use a list index, slice, or dictionary key as an argument to del, you remove the reference to the target item, slice, or key from the containing data structure. This may not imply the immediate removal of the referenced object from your computer’s memory.
In short, del doesn’t remove objects from memory and free up the used space. It only removes references to objects. This behavior may raise a question. If del doesn’t remove objects from memory, then how can you use del to release memory resources during your code’s execution?
To answer this question, you need to understand how Python manages the removal of objects from memory. In the following section, you’ll learn about Python’s garbage collection system and how it relates to using del for freeing up memory in your programs.