In Python, you can use the del statement to destroy an object.
The syntax is simple:
del object
For example, let’s create a variable and delete it:
num = 10 del num print(num)
Output:
NameError: name 'num' is not defined
What Can Be Deleted with ‘del’ in Python?
In Python, everything is an object. The del statement can be used to delete objects. Thus you can delete almost anything with it.
Here are some examples of items you can delete.
1. Delete Variables
Let’s create a variable num and delete it:
num = 10 del num print(num)
Output:
NameError: name 'num' is not defined
2. Delete Tuples
Even though a tuple is an immutable (unchangeable) object, you can still delete it as a whole.
For example:
nums = 1, 2, 3 del nums print(nums)
Output:
NameError: name 'nums' is not defined
However, you cannot use del to delete elements of a tuple. More about that later in this guide.
3. Delete Lists
A Python list is a mutable object. It is a sequence of values. This means you can either delete its elements or the object as a whole.
Here are some examples.
3.1. Delete an Entire List
names = ["Alice", "Bob", "Charlie"] del names print(names)
Output:
NameError: name 'names' is not defined
3.2. Delete an Element from a List
names = ["Alice", "Bob", "Charlie"] del names[0] print(names)
Output:
['Bob', 'Charlie']
3.3 Delete List Slices
If you are unfamiliar with slicing, check out this article.
In Python, slicing allows you to access, modify, and delete specific parts of an iterable.
For example, let’s remove every second element from a list:
names = ["Alice", "Bob", "Charlie", "David", "Emmanuel"] del names[::2] print(names)
Output:
['Bob', 'David']
4. Delete Dictionaries
A dictionary is a mutable collection of key-value pairs.
When it comes to using the del statement, you can delete a whole dictionary or specific key-value pairs.
4.1. Delete a Dictionary
data = {"age": 30, "name": "Alice", "job": "programmer"} del data print(data)
Output:
NameError: name 'data' is not defined
4.2. Delete Key-Value Pairs from Dictionaries
data = {"age": 30, "name": "Alice", "job": "programmer"} del data["age"] print(data)
Output:
{'name': 'Alice', 'job': 'programmer'}
5. Delete Functions
As already emphasized, everything is an object in Python. This applies to functions too.
This means you can delete a Python function using the del statement too.
For example:
def example(): return "Hello" del example print(example())
As a result, you are not able to call the function. Instead, you get this error:
NameError: name 'example' is not defined
6. Delete Classes
Even the implementation of a class is an object in Python. If you are confused by this, read more about metaclasses here.
Thus it is possible to delete a class from the code too.
For example, let’s write a class and delete it.
class Fruit: def __init__(self, name): self.name = name del Fruit banana = Fruit("Banana")
Now you see this error when trying to create objects from the class:
NameError: name 'Fruit' is not defined
6.1. Delete Objects
In Python, you can write a custom class and create objects from it.
These objects can be deleted using the del statement.
For instance:
class Fruit: def __init__(self, name): self.name = name banana = Fruit("Banana") del banana print(banana.name)
Output:
NameError: name 'banana' is not defined
6.2. Delete Object Attributes
You can also delete something that belongs to an object.
For example, let’s get rid of the name attribute from a Fruit object:
class Fruit: def __init__(self, name): self.name = name banana = Fruit("Banana") del banana.name print(banana.name)
Output:
AttributeError: 'Fruit' object has no attribute 'name'
What Cannot Be Deleted with ‘del’ in Python?
In Python, you can delete an immutable object. But you cannot use the del to modify the state of an immutable object. This means you cannot delete something that belongs to an immutable object.
In Python, tuples and strings are immutable objects. This means they cannot be changed after being created.
In other words, you cannot delete tuple elements or string characters with the del statement.
Let’s see examples.
1. Tuple Elements
Due to the immutability, you cannot change the state of a tuple after it has been created.
This means you cannot delete tuple elements with the del statement.
For instance:
nums = 1, 2, 3 del nums[1]
Output:
TypeError: 'tuple' object doesn't support item deletion
If you want to modify a tuple, such as removing elements from it, you need to create a modified copy of the tuple.
2. String Characters
Similar to a tuple, a string is an immutable object in Python. This means you cannot modify a string after creating it.
This means you cannot delete a character from a string using the del statement.
word = "Hello" del word[0]
Output:
TypeError: 'str' object doesn't support item deletion
To modify a string, such as removing a character, you need to create a modified copy of the string.
Del vs Assigning to None
When you want to free resources in Python, you can think of two solutions:
- Assigning to None.
- Deleting with the del Statement.
x = None
Or
del x
But what is the difference?
- The x = None approach keeps the variable name around. It just assigns a None to the variable, which frees up whatever it was referencing.
- The del x approach removes the variable and the reference so you cannot access the variable with the name anymore.