del
del removes a binding — a name from a namespace, an item or slice from a list or dict, an attribute from an object. It never destroys an object other references still point to.
del x
del nums[0] del d['key']
del nums[1:3] del nums[::2]
del obj.attr
del a, b[0], c.x
Demo
nums = [10, 20, 30, 40] del nums[0] nums
Compare the first two tabs: del nums[4] raises IndexError: list assignment index out of range (deletion reports as an assignment), while the slice 4:2 or -2:99 never raises — out-of-range slice bounds are clamped, and an empty range deletes nothing. A float bound (type 1e21 or more) is a TypeError in both. In the del name tab, the object is untouched; only the name a is gone from the namespace.
Syntax slots
| Name | Type | Required | Description |
|---|---|---|---|
| target | name / subscription / attribute | yes | Same forms as the left side of an assignment. A comma-separated list deletes each target left to right. |
Common patterns
if 'password' in user: del user['password'] # or: user.pop('password', None)
del history[100:]
del items[:]
frame = load_huge_frame() summary = frame.describe() del frame
Examples
Pitfalls
nums = [1, 2, 3, 4] for i in range(len(nums)): if nums[i] % 2 == 0: del nums[i]
nums = [1, 2, 3, 4] nums = [n for n in nums if n % 2 != 0] nums
data = [1, 2, 3] cache = {'data': data} del data cache['data']
data = [1, 2, 3] cache = {'data': data} data.clear() cache['data']
nums = [5, 2, 9] del nums[2] nums
nums = [5, 2, 9] nums.remove(2) nums
When to use
- Removing a dict key or list item when you do not need the removed value
- Removing a range of a list in place (del items[a:b])
- Dropping a large temporary so its memory can be reclaimed sooner
- You need the removed value → list.pop(i) / dict.pop(key)
- Removing by value → list.remove(x)
- Filtering many items → a comprehension builds the result in one pass
- Attribute name held in a string → delattr(obj, name)
Notes
FAQ
No — it deletes a reference (a name, an item slot, an attribute). The object is freed only when nothing refers to it any more. If another variable, list or dict still holds it, it stays alive.