Python del Keyword [With Examples]

Everything in Python is an object, and almost everything has attributes and methods. So the main objective of Python del is to delete the objects in the python programming language. Here object can be variables, lists, or parts of a list etc.

Each object is any kind of Python object. Usually, these are variables, but they can be functions, modules, classes.

The del statement works by unbinding the name, removing it from the set of names known to the Python interpreter. If this variable was the last remaining reference to an object, the object will be removed from memory. If, on the other hand, other variables still refer to this object, the object won’t be deleted.

How to delete or remove the element in Python

There are 3 different ways of removing or deleting elements in Python.

  1. remove
  2. del
  3. pop

But in this tutorial, we will learn about the working of Python del.

What is Python del?

The Python del is generally used to remove the variable from the local or global namespace. This is used to recover memory from data that is no longer needed.

Syntax of Python del

del obj_name

Here, del is a Python keyword. And, obj_name can be variables, user-defined objects, lists, items within lists, dictionaries etc.

Return Value of Python del

Python del statement doesn’t return anything.

Point to Be Noted

The del statement can be used to remove an item from a list by referring to its index, rather than its value.

Now let’s jump directly into examples and check out the working of Python del statement.

Python del Statement Examples

Let’s see some examples of del statement and try to delete some objects.

Example 1: Deleting a variable

var = "Python Pool"

del var

print(var)

Output:

  File "c:/Users/Karan/Desktop/test.py", line 5, in <module>
    print(var)
NameError: name 'var' is not defined

Here the output of the above example is ‘var’ is not defined. In this example, we get an error because the Python del operator deletes the variable. And now there is no variable named var stored in the memory.

Example 2: Deleting the First Item in a List

list = ["Learn", "Python", "Pool"]

del list[0]

print(list)

Output:

['Python', 'Pool']

Explanation:

In the above example, first, we have created our list named list. The above list contains three elements ( learn, python, pool ). After that, we deleted the first element of the list by using the operator del list[0]. Then we printed the list after deleting the first element of the list.

Example 3: Deleting the Last Item in a List

list = ["Learn", "Python", "Pool"]

del list[-1]

print(list)

Output:

['Learn', 'Python']

Explanation:

In the above example, first, we have created our list named list. The above list contains three elements ( learn, python, pool ). After that, we deleted the last element of the list by using the operator del list[-1]. Then we printed the list after deleting the last element of the list.

Example 4: Delete an User-Defined Object

Python Program to Delete a class’s object using Python del.

# Python Program to Delete a class's object

# defining a class
class student:
    name = "Karan"
    age = 22

# declaring object to the student class
std = student()

# printing values
print("Name: ", std.name)
print("Age: ", std.age)

# deleting the object 
del std

# printing values - will generate NameError
print("Name: ", std.name)
print("Age: ", std.age)

Output:

Name:  Karan
Age:  22
Traceback (most recent call last):
  File "c:/Users/Karan/Desktop/test.py", line 19, in <module>
    print("Name: ", std.name)
NameError: name 'std' is not defined

In the above example, we deleted the object std using del std. For the first time, we get our desired output. This is because we haven’t used the del keyword. But after using the del std in our object. We got the name error as the object is deleted from the memory.

Example 5: Deleting all the Elements in a Range

# initializing list  
lis = [16, 1, 34, 15, 904, 'Python', 'Pool'] 
  
# using del to delete elements from pos. 2 to 5 
# deletes 34, 15, 904
del lis[2 : 5] 
print(lis)

Output:

[16, 1, 'Python', 'Pool']

Explanation:

So, in this example, we have initialized a list with 7 elements in it. Then we deleted the elements in position 2 to 5. With the help of slicing and Python del keyword.

Example 6: Python Program to Remove a Key From a Dictionary

Dict = {'w':101,'x':102,'y':103,'z':104}
print(Dict)
if 'x' in Dict: 
    del Dict['x']
print(Dict)

Output:

{'w': 101, 'x': 102, 'y': 103, 'z': 104}
{'w': 101, 'y': 103, 'z': 104}

In the above example, we removed a key: value pair from a dictionary. We have 4 pair int the dictionary initially. After deleting the dictionary key x we only have 3 elements in the dictionary.

Python del: Additional Tips, Point to be Noted and Examples

You can’t delete items of tuples and strings. It’s because tuples and strings are immutables; objects that can’t be changed after its creation.


my_tuple = (1, 2, 3)

# Error: 'tuple' object doesn't support item deletion
del my_tuple[1]

However, you can delete an entire tuple or string.

my_tuple = (1, 2, 3)

# deleting tuple
del my_tuple

Difference Between remove, Python del and pop in Python

  • remove() delete the matching element/object whereas del and pop removes the element at a specific index.
  •  del and pop deals with the index. The only difference between the two is that- pop return deleted the value from the list and del does not return anything.
  • Pop is the only way that returns the object.
  • Remove is the only one that searches the object (not index).

In Summary: Use del to remove an element by index, pop to remove it by index if you need the returned value, and remove to delete an element by value.

Example of remove, Python del and pop

# (1) Remove an item with index
A = [1, 2, 4, 3, 4]
A.remove(4)
# This will print [1, 2, 3, 4]
print("Example 1 : A = {}".format(A))
 
# (2) Delete an item with index
A = [1, 2, 4, 3, 4]
del A[2]
# This will print [1, 2, 3, 4]
print("Example 2 : A = {}".format(A))
 
# (3) Delete all items
A = [1, 2, 4, 3, 4]
del A[:]
# This will print []
print("Example 3 : A = {}".format(A))
 
# (4) Delete a slice 2, 4
A = [1, 2, 4, 3, 4]
del A[1:3]
# This will print [1, 3, 4]
print("Example 4 : A = {}".format(A))
 
# (5) pop: remove and get the last item
A = [1, 2, 4, 3, 4]
x = A.pop()
# This will print [1, 2, 4, 3]
print("Example 5 : A = {}".format(A))
# This will print 4
print("Example 5 : x = {}".format(x))
 
# (6) pop with index: remove and get the second item
A = [1, 2, 4, 3, 4]
x = A.pop(1)
# This will print [1, 4, 3, 4]
print("Example 6 : A = {}".format(A))
# This will print 2
print("Example 6 : x = {}".format(x))

Output:

Example 1 : A = [1, 2, 3, 4]
Example 2 : A = [1, 2, 3, 4]
Example 3 : A = []
Example 4 : A = [1, 3, 4]
Example 5 : A = [1, 2, 4, 3]
Example 5 : x = 4
Example 6 : A = [1, 4, 3, 4]
Example 6 : x = 2

Running Time

Computational complexity (i.e. running time or Big-O) is as follows:

  • del O(n)
  • pop O(1)
  • remove O(n)

Note that these running times are the worst-case scenarios. For example, deleting an element at the beginning of the list takes constant time.

Which is the best way to delete the element in List?

  • If you want to delete a specific object in the list, use remove method.
  • If you want to delete the object at a specific location (index) in the list, you can either use del or pop.
  • Use the pop, if you want to delete and get the object at the specific location.

Difference Between Python del vs Assigning to None

The difference is that x = None will free whatever it referenced but keep the name around even though it’s just referencing None (which is a type, NoneType).

On the other hand, del x will completely remove both the name and what it referenced. If you thereafter try to use x a NameError will be thrown (or AttributeError in case of an object property).

So in practice, by assigning None to a name you can still use it in expressions while using del the name is completely removed. In the first case, a few bytes are needed to keep the name in memory, while the later completely clears all memory usage.

When should and shouldn’t I use the del keyword in Python?

Use the ‘del’ statement when you want to remove an item from a list and you know you will never need to reference that item again.

If you want to hang on to the removed list item for whatever reason, use the ‘pop’ method instead.

Must Read:

Conclusion

Python del is a useful keyword. Its syntax may be confusing at first. But once we use del more like an operator, not a method call, it is easy to remember.

Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints. Deleting a target list recursively deletes each target, from left to right.

Try to run the programs on your side and let me know if you have any queries.

Happy Coding!

Leave a Reply