del

Updated March 15, 2026 · Keywords
keyword variable memory

The del statement in Python removes variables, items from collections, attributes from objects, or names from a namespace. It is useful for cleaning up memory or removing specific elements from data structures.

Syntax

del variable_name              # Remove a variable
del list[index]               # Remove an item from a list
del dictionary[key]           # Remove an entry from a dictionary
del object.attribute          # Remove an attribute from an object
del variable1, variable2      # Remove multiple items

Removing Variables

When you delete a variable, Python removes the name from the current namespace and frees the associated memory (if no other references exist):

x = 10
print(x)
# Output: 10

del x

print(x)  # Raises NameError
# Output: NameError: name 'x' is not defined

Removing List Items

You can remove items from a list by index:

fruits = ["apple", "banana", "cherry", "date"]

del fruits[1]  # Remove second item
print(fruits)
# Output: ['apple', 'cherry', 'date']

# Remove a slice
numbers = [0, 1, 2, 3, 4, 5]
del numbers[2:5]  # Remove items at indices 2, 3, 4
print(numbers)
# Output: [0, 1, 5]

Removing Dictionary Entries

Delete key-value pairs from a dictionary:

person = {"name": "Alice", "age": 30, "city": "NYC"}

del person["age"]
print(person)
# Output: {'name': 'Alice', 'city': 'NYC'}

# Using del with a non-existent key raises KeyError
del person["country"]  # KeyError

Removing Object Attributes

Delete attributes from objects:

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

car = Car("Toyota", "Camry")
print(car.model)
# Output: Camry

del car.model
print(car.model)  # Raises AttributeError
# Output: AttributeError: 'Car' object has no attribute 'model'

Multiple Deletions

You can delete multiple items in one statement:

a, b, c = 1, 2, 3
del a, c
print(b)
# Output: 2

Common Use Cases

Cleaning up large data structures

import numpy as np

# Create a large array
data = np.random.rand(10000, 10000)

# Process data...

# Free memory when done
del data

# Force garbage collection
import gc
gc.collect()

Removing items during iteration

Be careful when modifying a list while iterating over it:

# Wrong way - causes unexpected behavior
numbers = [1, 2, 3, 4, 5]
for n in numbers:
    if n % 2 == 0:
        del n  # Only removes the variable, not the list item!

# Correct approach - use list comprehension
numbers = [1, 2, 3, 4, 5]
numbers = [n for n in numbers if n % 2 != 0]
print(numbers)
# Output: [1, 3, 5]

# Or iterate over a copy
numbers = [1, 2, 3, 4, 5]
for n in numbers[:]:  # iterate over a copy
    if n % 2 == 0:
        numbers.remove(n)
print(numbers)
# Output: [1, 3, 5]

Removing from a stack

class Stack:
    def __init__(self):
        self.items = []
    
    def push(self, item):
        self.items.append(item)
    
    def pop(self):
        if not self.items:
            return None
        item = self.items[-1]
        del self.items[-1]
        return item

stack = Stack()
stack.push(1)
stack.push(2)
print(stack.pop())
# Output: 2

del vs None

Setting a variable to None doesn’t remove it—it just assigns the value None:

x = 10
x = None
print(x)  # Works fine
# Output: None
print("x" in dir())  # x still exists
# Output: True

del x  # Actually removes the variable
print("x" in dir())  # x no longer exists
# Output: False

Practical Example

# Cache with automatic cleanup
class Cache:
    def __init__(self):
        self._data = {}
    
    def set(self, key, value):
        self._data[key] = value
    
    def get(self, key):
        return self._data.get(key)
    
    def delete(self, key):
        if key in self._data:
            del self._data[key]
            return True
        return False
    
    def clear(self):
        del self._data
        self._data = {}

cache = Cache()
cache.set("user", "Alice")
print(cache.get("user"))
# Output: Alice

cache.delete("user")
print(cache.get("user"))
# Output: None

See Also