del keyword in Python

The del keyword removes a name from local scope, global scope, removes one or more attributes from a class instance, removes elements from iterables. The Python examples remove names from various scopes and try accessing the same names again, printing the resulting NameError and AttributeError.

Keywords Updated 11 Sep 2019 3 min read

Overview

  • del statement removes a name from a scope.
  • After del statement is applied on a name, identity is lost for that name. Any reference to it afterwards will raise an exception of type NameError.
  • del statement can be applied in several contexts:
    • To delete a name from the local scope
    • To delete a name from the global scope
    • To delete an item from a list, set, dictionary or any other mutable Python iterable
    • To delete an attribute of a class instance. Remember, a class method cannot be deleted this way.
    • To delete a slicing from an iterable

Example - Removing a name from local and global scopes

python
# Python example program to remove names from global and local

# scopes using the Python keyword del

today = "Sunday";

def oddSequence():

    sum = 0;

    for i in range(1, 10, 2):

        print(i);

        sum = sum + i;

    # Prints the last value again

    print(i);

    # Print sum

    print("Sum %d"%sum);

    # Remove sum from local scope

    try:

        del sum;

        print(sum);

    except Exception as Ex:

        print(Ex);

    # Remove today from global scope

    global today;

    del today;

    # Remove i from local scope

    del i;

    # Already i has been unbound

    try:

        print(i);

    except Exception as Ex:

        print(Ex);

oddSequence();

# Today no longer available at global scope

print(today);

Output

Output
1

3

5

7

9

9

Sum 25

local variable 'sum' referenced before assignment

local variable 'i' referenced before assignment

Traceback (most recent call last):

  File "del0.py", line 40, in <module>

    print(today);

NameError: name 'today' is not defined

Example - Removing a reference to a class instance from global scope

python
# Example program that removes an object from

# the global scope

class X:

    def __init__(self, val):

        self.val = val

class Y:

    def __init__(self, val):

        self.val = val

class A:

    def __init__(self, x, y):

        self.x = x

        self.y = y

# Create instances of X and Y

x = X("one");

y = Y("two");

# Create instances of A.

# Instances of A have references to x and y instances.

a1 = A(x,y);

a2 = A(x,y);

# Removes a1 recursively. It will not remove object x from the scope.

del a1;

print(a2.x.val);

# Raises NameError

print(a1);

Overview

python
one

Traceback (most recent call last):

  File "del1.py", line 29, in <module>

    print(a1);

NameError: name 'a1' is not defined

Example - Removing a class attribute

python
class Robot:

    def __init__(self, id):

        self.id = id;

    def greet(self):

        print("Hello");

r1 = Robot("R1");

r1.greet();

# Delete the id attribute...possible

del r1.id;

try:

    print(r1.id); # Now id is no longer part of r1 instance

except Exception as Ex:

    print(Ex)

print("hi");

# Delete the function object - greet(), not possible

del r1.greet;

Output

Output
Hello

'Robot' object has no attribute 'id'

hi

Traceback (most recent call last):

  File "del2.py", line 20, in <module>

    del r1.greet;

AttributeError: greet

Example - Removing elements from Python iterables - list, dictionary using del

python
# Python example program to delete elements from iterables

listObject  = [5, 10, 15, 20, 25];

tupleObject = (2, 4, 6, 8, 10);

mapObject   = {1:"One", 2:"Two", 3:"Three", 4:"Four", 5:"Five", 6:"Six"};

# Remove an element from a Python list

print("Length of the list before removal of an element:%d"%len(listObject));

del listObject[0];

print("Length of the list after removal of an element:%d"%len(listObject));

# Remove a key and the corresponding value from a Python dictionary

print("Length of the dictionary before removal of an element:%d"%len(mapObject));

del mapObject[2];

print("Length of the dictionary after removal of an element:%d"%len(mapObject));

# Removal of an element from an immutable sequence is not possible

del tupleObject[1];

Output

Output
Length of the list before removal of an element:5

Length of the list after removal of an element:4

Length of the dictionary before removal of an element:6

Length of the dictionary after removal of an element:5

Traceback (most recent call last):

  File "del_elem.py", line 17, in <module>

    del tupleObject[1];

TypeError: 'tuple' object doesn't support item deletion