del — Intermediate Examples
Deletes a variable, list item, dictionary entry, or object attribute
del with slices and attributes
Advanced deletion targets.
python
# Delete a slice nums = list(range(10)) del nums[2:5] print(nums) # Delete every other element nums = list(range(10)) del nums[::2] print(nums) # Delete object attributes class Config: def __init__(self): self.debug = True self.verbose = True self.port = 8080 cfg = Config() print(vars(cfg)) del cfg.debug print(vars(cfg)) # del with __delitem__ class SafeDict(dict): def __delitem__(self, key): if key.startswith("_"): raise KeyError(f"Cannot delete private key: {key}") super().__delitem__(key) d = SafeDict({"name": "Alice", "_id": 1}) del d["name"] try: del d["_id"] except KeyError as e: print(f"Protected: {e}") print(d)
Expected Output
[0, 1, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
{'debug': True, 'verbose': True, 'port': 8080}
{'verbose': True, 'port': 8080}
Protected: 'Cannot delete private key: _id'
{'_id': 1}del can target slices, object attributes, and dict keys. Custom classes can control deletion behavior via __delitem__ and __delattr__.
del and garbage collection
Understanding what del actually does.
python
import sys # del removes the reference, not the object a = [1, 2, 3] b = a # b is another reference print(f"refcount before del: {sys.getrefcount(a) - 1}") del a # removes name 'a', but object still exists via 'b' print(f"b still works: {b}") # Object is garbage collected when refcount reaches 0 class Tracked: def __init__(self, name): self.name = name def __del__(self): print(f" {self.name} garbage collected") print("Creating objects:") t1 = Tracked("first") t2 = Tracked("second") print("Deleting first:") del t1 print("Deleting second:") del t2 print("Done")
del removes a name binding (reference), not the object itself. The object is garbage collected when its reference count reaches 0.
Want to try these examples interactively?
Open Intermediate Playground