How does the clear() method work in Python dictionaries?
a) Removes all key-value pairs from the dictionary
b) Removes a specific key-value pair from the dictionary
c) Adds a new key-value pair to the dictionary
d) Copies all key-value pairs to a new dictionary
Answer:
a) Removes all key-value pairs from the dictionary
Explanation:
The clear()
method in Python dictionaries removes all key-value pairs, effectively emptying the dictionary. After calling clear()
, the dictionary will be empty but still exist in memory.
# Example of clear() method
student = {"name": "John", "age": 20, "major": "Computer Science"}
student.clear()
print(student) # Output: {}
In this example, the clear()
method is used to remove all the key-value pairs from the student
dictionary, leaving it empty.
The clear()
method is useful when you need to reset a dictionary or remove all its contents without deleting the dictionary itself.