5.1.6 Deleting with del and clear()

Unit: Unit 5: Dictionaries and Sets • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Practice deleting specific keys with del and clearing with clear()
cache = {
    "query_1": [1, 2, 3],
    "query_2": [4, 5, 6],
    "query_3": [7, 8, 9]
}

# 1. Delete a specific key using 'del'
del cache["query_2"]
print("Cache after del:", list(cache.keys()))

# 2. Clear all remaining entries in-place using clear()
cache.clear()
print("Cache after clear:", cache)
print("Is cache empty:", len(cache) == 0)
Open in Live Interactive Python Sandbox →