Python del keyword

Python del keyword is used to delete a namespace or remove items in a sequence such as lists, dictionaries and sets.

Removing Variables and Objects

The primary use of the del keyword is to remove variables or objects from memory.

When you no longer need a variable or an object, using del ensures that it is promptly released, freeing up valuable system resources.

Consider the following example:

num = 20
print(num)

del num
print(num)

In the example above, del num removes the variable num from memory, making it inaccessible.

Attempting to access num after deletion results in a NameError since the variable no longer exists.

NameError: name 'num' is not defined. Did you mean: 'sum'?

Deleting Elements from Lists

The del keyword is particularly useful when working with lists.

It allows you to remove specific elements from a list based on their indices.

Here is an example:

nums = [1, 2, 3, 4, 5]
print(nums)

del nums[2] 
print(nums)

Output:

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

In the above example, del nums[2] removes the element at index 2 from the nums list, resulting in the updated list [1, 2, 4, 5]. This functionality comes in handy when you need to selectively delete specific elements without altering the remaining items.

Deleting Slices from Lists

You can also utilize the del keyword to remove a range of elements from a list using slice notation.

Consider the following example:

nums = [1, 2, 3, 4, 5]
print(nums)

del nums[1:4]
print(nums)

Output:

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

Here, del nums[1:4] removes elements from index 1 to 3 (exclusive) from the nums list, resulting in the updated list [1, 5]. This technique allows you to efficiently remove a range of elements in a single line of code.

Deleting Attributes from Objects

The del keyword is not limited to variables and lists; it can also be used to delete attributes from objects.

Consider the following example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Steve", 25)
print(person.name)

del person.name
print(person.name)

Output:

AttributeError: 'Person' object has no attribute 'name'

In this example, del person.name removes the name attribute from the person object.
Attempting to access person.name after deletion raises an AttributeError since the attribute no longer exists.

Conclusion

The del keyword is a versatile tool in Python that allows you to efficiently remove variables

Leave a Reply

Your email address will not be published. Required fields are marked *