Python del

Python del keyword is used for deleting. You can use it to remove variables, items from lists, parts of dictionaries, or even attributes from objects. It's essentially a way to tell Python that you no longer need a specific piece of data or a variable. Understanding how Python del works is important for managing program's memory and keeping code clean and efficient.
Table of Contents

What is the Use of del in Python?

Python del statement is used to delete objects. When you no longer need a variable, a list element, a dictionary item, or even an attribute of an object, you can use it to remove it from memory. This can help manage resources, especially when dealing with large objects that are no longer needed. Python del statement provides fine-grained control over what gets removed from your program’s namespace and memory. It can remove variables, making them undefined, or it can remove elements from data structures.

Python del Syntax

del object

Explanation

  • del: This is the keyword that indicates you want to delete something.
  • object: This is the name of the variable, list element, dictionary item, object attribute, etc., that you want to delete. It could be del my_variable, del my_list[0], del my_dict['key'], or del my_object.attribute.

Python del Example

my_variable = 10
print(my_variable)

del my_variable
print(my_variable)  # Error

Explanation

  • my_variable = 10: Creates a variable named my_variable and assigns it the value 10.
  • print(my_variable): Prints the value of my_variable, which is 10.
  • del my_variable: This uses Python del to delete the variable my_variable.
  • print(my_variable): This line will now cause a NameError because my_variable no longer exists.

Using del vs Assigning None

You might wonder whether to use del to remove an object or assign it the value None. Python del removes the object and its association with its name from the namespace. Assigning None to a variable, on the other hand, changes the variable’s value; it does not delete the variable name; it reassigns the name to the value None. The original object might still be in memory if other variables reference it. Use del when you want to remove an object and its name binding altogether; use None to indicate that a variable does not currently hold a meaningful value but may be used later.

Syntax

# Using del:
del object

# Assigning None:
object = None

Explanation

  • del object: This uses the Python del keyword to completely remove object from memory and its name from the namespace.
  • object = None: This reassigns the variable name object to the value None. The original object may still exist if something else is referencing it.

Example

a = [1, 2, 3]
b = a
del a
print(b)

x = [4, 5, 6]
y = x
x = None
print(y)

Explanation

  • a = [1, 2, 3]: Creates a list a.
  • b = a: Makes b refer to the same list object as a.
  • del a: Deletes the name a. The list object still exists because b is referencing it.
  • print(b): Prints [1, 2, 3] because b still refers to the list.
  • x = [4, 5, 6]: Creates another list x.
  • y = x: Makes y refer to the same list object as x.
  • x = None: Reassigns x to None. The list object still exists because y is referencing it.
  • print(y): Prints [4, 5, 6] because y still refers to the list.

Output

[1, 2, 3]
[4, 5, 6]


Deleting Variables

You can use the Python del statement to delete variables entirely. When you delete a variable using del, its name is removed from the current namespace. This means you can no longer access the variable or the value it referenced unless you redefine it. If no other variables are referencing the deleted variable’s value, that value might also be garbage collected (removed from memory).

Example

data = "This is some important data"
print(data)

del data

print(data)  # This will cause a NameError

Explanation

  • data = "This is some important data": This creates a variable named data and assigns it a string value.
  • print(data): This prints the value of data, which is “This is some important data”.
  • del data: This uses Python del to delete the variable data.
  • print(data): This line now causes a NameError because data no longer exists in the namespace.

Delete a User-Defined Object

You can use the del statement to delete user-defined objects like you would delete built-in objects. When you use Python del on an object, it decrements the reference count of that object. If the reference count drops to zero (meaning nothing else is referring to the object), Python’s garbage collector may eventually reclaim the memory occupied by the object. It’s important to remember that del doesn’t directly call the object’s destructor (__del__ method if it has one); instead, the destructor might get called later by the garbage collector when the object is no longer reachable.

Example

class MyClass:
    def __init__(self, name):
        self.name = name
        print(f"Object {self.name} created")

    def __del__(self):
        print(f"Object {self.name} is being destroyed")

obj1 = MyClass("Object 1")
obj2 = obj1
del obj1
print("obj1 deleted, but obj2 still exists")
del obj2
print("obj2 deleted")

Explanation

  • class MyClass:: Defines a class named MyClass.
  • def __init__(self, name):: The constructor for MyClass.
  • self.name = name: Stores the name in the object.
  • print(f"Object {self.name} created"): Prints a message when an object is created.
  • def __del__(self):: The destructor for MyClass. This will be called when the object is about to be destroyed.
  • print(f"Object {self.name} is being destroyed"): Prints a message when an object is destroyed.
  • obj1 = MyClass("Object 1"): Creates an instance of MyClass named obj1.
  • obj2 = obj1: Makes obj2 refer to the same object as obj1. The reference count of the object increases.
  • del obj1: Deletes the name obj1. The object is not destroyed yet because obj2 still refers to it. The reference count decreases.
  • print("obj1 deleted, but obj2 still exists"): Prints a message.
  • del obj2: Deletes the name obj2. Now the object has no more references, so it’s eligible for garbage collection, and the destructor is called. The reference count decreases to 0.
  • print("obj2 deleted"): Prints a message.

Output

Object Object 1 created
obj1 deleted, but obj2 still exists
Object Object 1 is being destroyed
obj2 deleted


Deleting Items from a List

Python del statement helps remove items from a list. You can delete an item at a specific index using del list[index]. Remember that list indices start at 0, so del my_list[0] removes the first element, del my_list[1] removes the second, and so on. After deleting an item, the elements to the right of the deleted item shift to the left to fill the gap, and the list’s length is reduced.

Example

my_list = ['apple', 'banana', 'cherry', 'date']
print(f"Original list: {my_list}")

del my_list[1]
print(f"List after deleting element at index 1: {my_list}")

del my_list[0]
print(f"List after deleting element at index 0: {my_list}")

Explanation

  • my_list = ['apple', 'banana', 'cherry', 'date']: Creates a list named my_list with four string elements.
  • print(f"Original list: {my_list}"): Prints the original list: ['apple', 'banana', 'cherry', 'date'].
  • del my_list[1]: Uses Python del to remove the element at index 1 (the second element, ‘banana’).
  • print(f"List after deleting element at index 1: {my_list}"): Prints the modified list: ['apple', 'cherry', 'date'].
  • del my_list[0]: Removes the element at index 0 (the first element, ‘apple’).
  • print(f"List after deleting element at index 0: {my_list}"): Prints the final list: ['cherry', 'date'].

Output

Original list: [‘apple’, ‘banana’, ‘cherry’, ‘date’]
List after deleting element at index 1: [‘apple’, ‘cherry’, ‘date’]
List after deleting element at index 0: [‘cherry’, ‘date’]


Deleting an Item, Slice from a List

Python del allows you to delete slices from a list. A slice is a portion of a list specified by a range of indices. To delete a slice, you use the syntax del list[start:end], where start is the starting index (inclusive) and end is the ending index (exclusive). This removes all elements from start up to (but not including) end. If you omit start, it defaults to 0; if you omit end, it defaults to the list’s length.

Example

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(f"Original list: {my_list}")

del my_list[2:5]
print(f"List after deleting slice from index 2 to 5: {my_list}")

del my_list[:3]
print(f"List after deleting slice from beginning to index 3: {my_list}")

del my_list[::2]
print(f"List after deleting every other element: {my_list}")

Explanation

  • my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: Creates a list of numbers from 0 to 9.
  • print(f"Original list: {my_list}"): Prints the original list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
  • del my_list[2:5]: Deletes the slice from index 2 up to (but not including) index 5. This removes elements 2, 3, and 4.
  • print(f"List after deleting slice from index 2 to 5: {my_list}"): Prints the modified list: [0, 1, 5, 6, 7, 8, 9].
  • del my_list[:3]: Deletes the slice from the beginning of the list up to (but not including) index 3. This removes elements 0, 1, and 5.
  • print(f"List after deleting slice from beginning to index 3: {my_list}"): Prints the list: [6, 7, 8, 9].
  • del my_list[::2]: Deletes every other element starting from the beginning.
  • print(f"List after deleting every other element: {my_list}"): Prints the list: [7, 9].

Output

Original list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
List after deleting slice from index 2 to 5: [0, 1, 5, 6, 7, 8, 9]
List after deleting slice from beginning to index 3: [6, 7, 8, 9]
List after deleting every other element: [7, 9]


Remove a key:value Pair from a Dictionary

Python del statement can be used to remove key-value pairs from a dictionary. You specify the key you want to delete using the syntax del dict[key]. This removes the key and its associated value from the dictionary. If the key doesn’t exist, a KeyError is raised.

Example

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(f"Original dictionary: {my_dict}")

del my_dict['b']
print(f"Dictionary after deleting key 'b': {my_dict}")

del my_dict['d']
print(f"Dictionary after deleting key 'd': {my_dict}")

Explanation

  • my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}: Creates a dictionary with four key-value pairs.
  • print(f"Original dictionary: {my_dict}"): Prints the original dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}.
  • del my_dict['b']: Deletes the key-value pair where the key is ‘b’.
  • print(f"Dictionary after deleting key 'b': {my_dict}"): Prints the modified dictionary: {'a': 1, 'c': 3, 'd': 4}.
  • del my_dict['d']: Deletes the key-value pair where the key is ‘d’.
  • print(f"Dictionary after deleting key 'd': {my_dict}"): Prints the final dictionary: {'a': 1, 'c': 3}.

Output

Original dictionary: {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
Dictionary after deleting key ‘b’: {‘a’: 1, ‘c’: 3, ‘d’: 4}
Dictionary after deleting key ‘d’: {‘a’: 1, ‘c’: 3}


Deleting Members from Custom Classes

Python del can be used to delete attributes (members) from instances of custom classes. You use the syntax del object.attribute to remove a specific attribute from an object. This makes the attribute inaccessible through that object. It’s like removing a variable that belongs to that specific object. Remember that this only affects the particular instance, not the class definition or other instances of the same class.

Example

class MyClass:
    def __init__(self, a, b):
        self.attr1 = a
        self.attr2 = b

    def display(self):
        print(f"attr1: {self.attr1}, attr2: {self.attr2}")

obj = MyClass(10, 20)
obj.display()

del obj.attr1
# obj.display()  # This would now cause an AttributeError

print(obj.attr2)
# print(obj.attr1)

Explanation

  • class MyClass:: Defines a class named MyClass.
  • def __init__(self, a, b):: The constructor that takes two arguments, a and b.
  • self.attr1 = a and self.attr2 = b: Assigns the values of a and b to the attributes attr1 and attr2, respectively.
  • def display(self):: A method to display the attributes.
  • print(f"attr1: {self.attr1}, attr2: {self.attr2}"): Prints the values of attr1 and attr2.
  • obj = MyClass(10, 20): Creates an instance of MyClass named obj with attr1 set to 10 and attr2 set to 20.
  • obj.display(): Calls the display method to print the attributes: attr1: 10, attr2: 20.
  • del obj.attr1: Deletes the attribute attr1 from the obj instance.
  • # obj.display(): If you uncomment this line, it will raise an AttributeError because attr1 no longer exists for obj.
  • print(obj.attr2): This still works and prints 20 because attr2 was not deleted.
  • print(obj.attr1): This line is commented out because it would raise an AttributeError.

Output

attr1: 10, attr2: 20
20


Removing an Instance Attribute

Python del can remove attributes from instances of custom classes. However, it’s important to understand that this only removes the attribute from that specific instance, not from the class or other instances. When you use del object.attribute, you’re essentially deleting the attribute from the object’s namespace. This can be useful for dynamically modifying objects during runtime. Still, it should be done cautiously, as it can lead to AttributeError exceptions if you try to access the deleted attribute later.

Example

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name)

del my_dog.name

# print(my_dog.name)  # This would raise an AttributeError
print(my_dog.breed)  # This still works

other_dog = Dog("Lucy", "Labrador")
print(other_dog.name)  # Other instances are unaffected

Explanation

  • class Dog:: Defines a class named Dog.
  • def __init__(self, name, breed):: The constructor for Dog, taking name and breed as arguments.
  • self.name = name and self.breed = breed: Initializes the name and breed attributes for a Dog instance.
  • my_dog = Dog("Buddy", "Golden Retriever"): Creates a Dog instance named my_dog.
  • print(my_dog.name): Prints the name of my_dog, which is “Buddy”.
  • del my_dog.name: Removes the name attribute from the my_dog instance.
  • # print(my_dog.name): This line is commented out because it would raise an AttributeError as name has been deleted.
  • print(my_dog.breed): This still works and prints “Golden Retriever” because breed was not deleted.
  • other_dog = Dog("Lucy", "Labrador"): Creates another Dog instance.
  • print(other_dog.name): Prints “Lucy”, showing that deleting name from my_dog did not affect other instances.

Output

Buddy
Golden Retriever
Lucy


Preventing Attribute Deletion in Custom Classes

What if you want to prevent the deletion of specific attributes in your custom classes? You can achieve this by overriding the __delattr__ method in your class. The __delattr__ method is called when the del statement is used on an attribute of an instance of your class. By default, it deletes the attribute. However, you can override it to raise an exception or do nothing, simply preventing the deletion.

Example

class ProtectedClass:
    def __init__(self):
        self._protected = "This cannot be deleted"
        self.normal = "This can be deleted"

    def __delattr__(self, name):
        if name == "_protected":
            raise AttributeError("Cannot delete protected attribute")
        else:
            super().__delattr__(name)

obj = ProtectedClass()
print(obj._protected)
print(obj.normal)

del obj.normal  # This is allowed

# del obj._protected  # This will raise an AttributeError

Explanation

  • class ProtectedClass:: Defines a class named ProtectedClass.
  • def __init__(self):: The constructor.
  • self._protected = "This cannot be deleted": Initializes a “protected” attribute.
  • self.normal = "This can be deleted": Initializes a regular attribute.
  • def __delattr__(self, name):: Overrides the __delattr__ method.
  • if name == "_protected":: Checks if the attribute being deleted is _protected.
  • raise AttributeError("Cannot delete protected attribute"): Raises an error if someone tries to delete _protected.
  • else: super().__delattr__(name): If it’s not _protected, the default deletion behavior is executed.
  • obj = ProtectedClass(): Creates an instance of ProtectedClass.
  • print(obj._protected): Prints the value of _protected.
  • print(obj.normal): Prints the value of normal.
  • del obj.normal: Deletes the normal attribute.
  • # del obj._protected: This line is commented out because it would raise an AttributeError.

Output

This cannot be deleted
This can be deleted


del With Tuples and Strings

Tuples and strings in Python are immutable. This means that their contents cannot be changed once they are created. Therefore, you cannot use Python del to delete individual elements from a tuple or characters from a string. If you try to do so, you’ll get a TypeError. However, you can use del to delete the entire tuple or string variable itself.

Example

my_tuple = (1, 2, 3)
# del my_tuple[0]  # This would raise a TypeError

my_string = "hello"
# del my_string[0]  # This would raise a TypeError

del my_tuple
del my_string

# print(my_tuple)  # This would raise a NameError
# print(my_string)  # This would raise a NameError

Explanation

  • my_tuple = (1, 2, 3): Creates a tuple named my_tuple.
  • # del my_tuple[0]: This line is commented out because it would raise a TypeError.
  • my_string = "hello": Creates a string named my_string.
  • # del my_string[0]: This line is commented out because it would raise a TypeError.
  • del my_tuple: Deletes the entire my_tuple variable.
  • del my_string: Deletes the entire my_string variable.
  • # print(my_tuple) and # print(my_string): These lines are commented out because they would raise NameError since the variables have been deleted.

When Should and Shouldn’t We Use the del Keyword in Python?

When to use del:

  • Memory Management: When working with large objects and you’re sure you no longer need them, del can help free up memory.
  • Removing List Elements/Slices: del is the standard way to remove elements or slices from lists.
  • Removing Dictionary Key-Value Pairs: del is used to remove entries from dictionaries.
  • Deleting Object Attributes: When removing an attribute from a specific object instance.
  • Cleanup: When you want to explicitly remove variables from the namespace to avoid accidental usage later in your code.

When not to use del:

  • Immutable Objects (Tuples, Strings): You can’t delete parts of tuples or strings; you can only delete the entire variable.
  • Relying on Garbage Collection: In many cases, Python’s garbage collector will handle memory management for you. Don’t overuse del if it’s not necessary.
  • As a Performance Optimization (Prematurely): Don’t assume del will always lead to significant performance improvements. Profile your code first.
  • When None is Sufficient: If you just want to indicate that a variable doesn’t hold a meaningful value, assigning None might be more appropriate.

Conclusion

The Python del statement manages objects and their attributes. It provides a way to explicitly remove variables, list elements, dictionary items, and object attributes from memory, which can be valuable for resource management, code clarity, and dynamic object modification. However, using del judiciously and understanding its implications is essential, especially when dealing with mutable and immutable objects. While Python’s automatic garbage collection handles much of the behind-the-scenes memory management, del gives you fine control when needed.


Python Reference

Python del

Table of Contents