del statement
del removes a name, a list item, a slice of a list or a dictionary key. It deletes the reference, not necessarily the object itself.
del name
del items[index]
del items[start:stop]
del mapping[key]del removes things by position or by name. del scores[0] drops the first list item, del prices["tea"] removes a dictionary entry, and del x forgets the variable x entirely.
Use it when you know where something is. To remove by value from a list, use list.remove(); to remove and get the value back, use list.pop() or dict.pop().
del x deletes the name, not the object. If another name still points at the same list, the list lives on. Python frees the memory only when nothing refers to the object any more.
Examples
1Remove a list item by position
queue = ["Ali", "Bea", "Cai", "Dev"]
del queue[1]
print(queue)
del queue[-1]
print(queue)['Ali', 'Cai', 'Dev'] ['Ali', 'Cai']
2Remove a slice
readings = [10, 11, 99, 98, 12, 13]
del readings[2:4]
print(readings)[10, 11, 12, 13]
3Remove a dictionary key
settings = {"theme": "dark", "font": 14, "beta": True}
del settings["beta"]
print(settings)
if "missing" in settings:
del settings["missing"]
print(len(settings)){'theme': 'dark', 'font': 14}
2Deleting a key that is not there raises KeyError, so check with in first, or use settings.pop(key, None).
4Delete a variable
temp = 42
del temp
try:
print(temp)
except NameError:
print("NameError: temp no longer exists")NameError: temp no longer exists
5del removes a name, not the object
team = ["Mia", "Noah"]
same_team = team
del team
print(same_team)['Mia', 'Noah']
Common mistakes
Deleting from a list while looping over it
Positions shift after every del, so the loop skips items. Build a new list with a comprehension instead.
nums = [1, 2, 2, 3]
nums = [n for n in nums if n != 2]
print(nums)[1, 3]
Calling del like a function
del(x) works but looks like a function call. del is a statement: write del x, and del a, b to remove several.
Questions people ask
del vs remove vs pop?
del items[i] removes by position and returns nothing. items.remove(v) removes the first item equal to v. items.pop(i) removes by position and gives the item back.
How do I empty a whole list?
items.clear() or del items[:]. Both keep the same list object, so other names see it empty too.
Does del free memory?
Only when no other name points at the object. Python then frees it automatically.