What does del do in python dictionary?

The Python del keyword is used to delete objects. Its syntax is:

# delete obj_name
del obj_name

Here, obj_name can be variables, user-defined objects, lists, items within lists, dictionaries etc.


Example 1: Delete an user-defined object


class MyClass:
    a = 10
    def func(self):
        print('Hello')

# Output: 
print(MyClass)

# deleting MyClass
del MyClass

# Error: MyClass is not defined
print(MyClass)	

In the program, we have deleted MyClass using del MyClass statement.


Example 2: Delete variable, list, and dictionary


my_var = 5
my_tuple = ('Sam', 25)
my_dict = {'name': 'Sam', 'age': 25}

del my_var
del my_tuple
del my_dict

# Error: my_var is not defined
print(my_var)

# Error: my_tuple is not defined
print(my_tuple)

# Error: my_dict is not defined
print(my_dict)

Example 3: Remove items, slices from a list

The del statement can be used to delete an item at a given index. It can also be used to remove slices from a list.

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# deleting the third item
del my_list[2]

# Output: [1, 2, 4, 5, 6, 7, 8, 9]
print(my_list)

# deleting items from 2nd to 4th
del my_list[1:4]

# Output: [1, 6, 7, 8, 9]
print(my_list)

# deleting all elements
del my_list[:]

# Output: []
print(my_list)

Example 4: Remove a key:value pair from a dictionary

person = { 'name': 'Sam',
  'age': 25,
  'profession': 'Programmer'
}

del person['profession']

# Output: {'name': 'Sam', 'age': 25}
print(person)

del With Tuples and Strings

Note: You can't delete items of tuples and strings in Python. It's because tuples and strings are immutables; objects that can't be changed after their 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

There is a specific example of when you should use del (there may be others, but I know about this one off hand) when you are using sys.exc_info() to inspect an exception. This function returns a tuple, the type of exception that was raised, the message, and a traceback.

The first two values are usually sufficient to diagnose an error and act on it, but the third contains the entire call stack between where the exception was raised and where the the exception is caught. In particular, if you do something like

try:
    do_evil()
except:
    exc_type, exc_value, tb = sys.exc_info()
    if something(exc_value):
        raise

the traceback, tb ends up in the locals of the call stack, creating a circular reference that cannot be garbage collected. Thus, it is important to do:

try:
    do_evil()
except:
    exc_type, exc_value, tb = sys.exc_info()
    del tb
    if something(exc_value):
        raise

to break the circular reference. In many cases where you would want to call sys.exc_info(), like with metaclass magic, the traceback is useful, so you have to make sure that you clean it up before you can possibly leave the exception handler. If you don't need the traceback, you should delete it immediately, or just do:

exc_type, exc_value = sys.exc_info()[:2]

To avoid it all together.

Python del OperatorUse del to remove one or more elements from a collection. Invoke del on lists and dictionaries.

Del built-in. This operator stands for "delete." The syntax for del is a bit unusual—it works more like the "in" operator than a method.

In

Operator details. With del, we specify a list, dictionary or other collection. We pass an index or key we want to remove. On lists, we can remove slices (ranges of elements) at once.

Del examples. Here we call del to remove the third element in a list. We compare this to the remove() method on list, which searches for the first matching value and then deletes it.

Tip To use del on a list we must specify an index or a slice. We cannot use del to search for a value.

Note Del is a clear and fast way to remove elements from a list. Often we can use it instead of the remove() method.

values = [100, 200, 300, 400, 500, 600] # Use del to remove by an index or range of indexes. del values[2] print(values) values = [100, 200, 300, 400, 500, 600] # Use remove to remove by value. values.remove(300) print(values)

[100, 200, 400, 500, 600] [100, 200, 400, 500, 600]

Remove. This method is available on lists. It searches for the first element that has the specified value and removes it from the list.

Tip The implementation of remove() involves a search. This makes it slower than del.

has_duplicates = [10, 20, 20, 20, 30] # The remove method on list does not remove more than the first match. has_duplicates.remove(20) print(has_duplicates)

[10, 20, 20, 30]

Syntax. Slice syntax is supported with the del built-in on a list. So we can remove a range of elements based on a slice. This is a good way to resize a list.

Resize List

First argument Before the ":" we specify the start index of the region we want to remove.

Second argument This is the end index (not the count) of the target region. If no ":" is present, only one element is removed.

elements = ["A", "B", "C", "D"] # Remove first element. del elements[:1] print(elements) elements = ["A", "B", "C", "D"] # Remove two middle elements. del elements[1:3] print(elements) elements = ["A", "B", "C", "D"] # Remove second element only. del elements[1] print(elements)

['B', 'C', 'D'] ['A', 'D'] ['A', 'C', 'D']

Dictionary, del. We can use del on a dictionary. We pass the key we want to remove. It removes both the key and its associated value. Only one entry can be removed at a time.

Dictionary

colors = {"red" : 100, "blue" : 50, "purple" : 75} # Delete the pair with a key of "red." del colors["red"] print(colors)

{'blue': 50, 'purple': 75}

Benchmark, del. This example benchmarks the del operator on a list against remove(). It is not perfect—the del code removes by index, but remove() searches by value.

Version 1 This version of the code uses the del operator to remove a certain value from a list.

Version 2 Here we call remove() instead of using del. This searches the list by value (unlike del).

Result The del keyword is a faster way to remove an element than the remove method. It requires no searching.

import time print(time.time()) # Version 1: use del on an index. for i in range(0, 2000000): values = [x for x in range(100)] del values[95] if len(values) != 99: break print(time.time()) # Version 2: use list remove method on a value. for i in range(0, 2000000): values = [x for x in range(100)] values.remove(95) if len(values) != 99: break print(time.time())

1415214840.25 1415214841.46 1.21 s, del 1415214842.85 1.39 s, remove

String error. Del cannot be used on a string. It might make sense for it to remove characters, but this does not work. We use del on collections, not strings.

location = "beach" # Cannot remove part of a string with del. del location[1] print(location)

Traceback (most recent call last): File "C:\programs\file.py", line 6, in del location[1] TypeError: 'str' object doesn't support item deletion

A summary. 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.

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

No updates found for this page.

How does Del work in Python dictionary?

Definition and Usage. The del keyword is used to delete objects. In Python everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list etc.

What does Del do to a dictionary?

In a dictionary, Python del can be used to delete a specific key-value pair. For deleting a specific data element in the dictionary, the del statement only accepts the key as an index value.

What is the purpose of Del?

Del is used as a shorthand form to simplify many long mathematical expressions. It is most commonly used to simplify expressions for the gradient, divergence, curl, directional derivative, and Laplacian.

What is __ del __ in Python?

The __del__() method is a known as a destructor method. It is called when an object is garbage collected which happens after all references to the object have been deleted.