all Python 3Arithmetic & operatorsconstruct
del
assignment
The del statement removes a name, an item, a slice or an attribute. It removes a reference, not the object: the object lives while anything else still refers to it.
Syntax
del name
del seq[i]
del seq[start:stop:step]
del d[key]
del obj.attr
After del x, using x raises NameError, and inside a function UnboundLocalError. If b also refers to the list, del a leaves the data alone: the garbage collector frees the list once the last reference is gone, and only then is __del__ called — so del obj and obj.__del__() are not the same thing at all. To empty a list that other names see, use del a[:] or a.clear(), not del a. del lst[i] shifts the tail, so deleting by index while looping forward goes wrong — the indices drift.
Examples
a = [1, 2, 3]
b = a
del a # удалили имя, а не список
print(b) # → [1, 2, 3]
print(a) # → NameError: name 'a' is not defined
nums = list(range(10))
del nums[::2]
print(nums) # → [1, 3, 5, 7, 9]
d = {'x': 1, 'y': 2}
del d['x']
print(d) # → {'y': 2}
class P:
pass
p = P()
p.age = 30
del p.age
print(hasattr(p, 'age')) # → False
class Res:
def __del__(self):
print('объект удалён')
r = Res()
alias = r
del r
print('после del r') # → после del r — объект ещё жив
del alias # → объект удалён — ушла последняя ссылка (CPython)
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy