Python del Statement

delete a Python object with the del statement

The del statement in Python is used to delete objects.

The syntax is:

del object

For instance, 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 the del Statement 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.

Variables

Let’s create a variable num and delete it:

num = 10
del num

print(num)

Output:

NameError: name 'num' is not defined

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:





However, you cannot use del to delete elements of a tuple. More about that later in this guide.

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.

Delete a List

names = ["Alice", "Bob", "Charlie"]

del names

print(names)

Output:

NameError: name 'names' is not defined

Delete an Element from a List

names = ["Alice", "Bob", "Charlie"]

del names[0]

print(names)

Output:

['Bob', 'Charlie']

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']

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.

Delete a Dictionary

data = {"age": 30, "name": "Alice", "job": "programmer"}

del data

print(data)

Output:

NameError: name 'data' is not defined

Delete Key-Value Pairs from Dictionaries

data = {"age": 30, "name": "Alice", "job": "programmer"}

del data["age"]

print(data)

Output:

{'name': 'Alice', 'job': 'programmer'}

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

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

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

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 Statement 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.

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.

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 to.
  • The del x approach removes the variable and the reference so you cannot access the variable with the name anymore.

Conclusion

Thanks for reading.

Happy coding!

Further Reading

50 Python Interview Questions

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.