del — Intermediate Playground
Deletes a variable, list item, dictionary entry, or object attribute
Python Playground
# 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)
Output
Click "Run" to execute your code
del can target slices, object attributes, and dict keys. Custom classes can control deletion behavior via __delitem__ and __delattr__.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?