Python del keyword

Last Updated : 23 Jul, 2026

The del keyword is used to remove references to objects in Python. It can delete variables, list elements, dictionary entries, object attributes, and slices of mutable sequences. If an object no longer has any references after deletion, Python automatically reclaims its memory through garbage collection.

Example: The following code deletes a variable.

Python
name = "GeeksforGeeks"
del name
print(name)

Output

NameError: name 'name' is not defined

Syntax

There are more than one ways to use del keyword:

1. del object_name

2. del object_name[index]

3. del object_name[start:stop]

Parameters

  • object_name: The object to delete.
  • index: The element position to remove.
  • start:stop: The slice range to delete.

Deleting Variables

The del keyword can remove one or multiple variables.

Example:

Python
a = 20
b = "GeeksforGeeks"
del a, b
print(a)
print(b)

Output

NameError: name 'a' is not defined

Removing References to Objects and Classes

The del keyword can also remove references to user-defined objects and classes. However, it does not immediately delete the object from memory. Python automatically reclaims the memory when no references to the object remain.

Example:

Python
class GfgClass:
    a = 20

obj = GfgClass()
del obj
del GfgClass

Explanation:

  • obj = GfgClass() creates an instance of the class.
  • del obj removes the reference to the object.
  • del GfgClass removes the class definition from the current namespace.
  • The actual memory is freed only when there are no remaining references.

List Slicing Using del Keyword

In the program below we will delete some parts of a list (basically slice the list) using del keyword.

Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
del a[1]
print(a)
del a[3:5]
print(a)

Output
[1, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 4, 7, 8, 9]

Explanation:

  • del a[1] removes the element at index 1.
  • del a[3:5] removes elements from index 3 up to (but not including) index 5.

Deleting Dictionary Entries

del can remove specific key-value pairs from a dictionary.

Python
d = {

    "small": "big",

    "black": "white",

    "up": "down"
}
del d["black"]
print(d)

Output
{'small': 'big', 'up': 'down'}

Explanation:

  • del d["black"] removes the key-value pair associated with "black".
  • The remaining entries stay unchanged.

Deleting Objects and Classes

del can also remove references to objects and classes.

Python
class GfgClass:
    a = 20

obj = GfgClass()
del obj
del GfgClass

Explanation:

  • del obj removes the reference to the object.
  • del GfgClass removes the class definition from the current namespace.
  • The actual memory is freed only when no references remain.

Please refer delattr() and del() for more details.

Comment