English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The clear() method deletes all items from the dictionary.
The syntax of clear() is:
dict.clear()
clear() without any parameters
The clear() method does not return any value (returns None).
d = {1: "one", 2: "two" d.clear() print('d =', d)
When running the program, the output is:
d = {}
You can also delete all elements from the dictionary by assigning an empty dictionary {}.
However, if there are other variables referencing the dictionary, then calling clear() and assigning {} have differences.
d = {1: "one", 2: "two" d1 = d d.clear() print('Delete items using clear()') print('d =', d) print('d1 =, d1) d = {1: "one", 2: "two" d1 = d d = {} print('Delete items through allocation {}') print('d =', d) print('d1 =, d1)
When running the program, the output is:
Delete items using clear() d = {} d1 = {} Delete items through allocation {} d = {} d1 = {1: 'one', 2: 'two'