English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The clear() method removes all items from the dictionary.
The syntax of clear() is:
dict.clear()
clear() method 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 remove all elements from the dictionary by assigning an empty dictionary {}.
However, if there are other variables referencing the dictionary, there is a difference between calling clear() and assigning {}.
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 by allocation {}') print('d =', d) print('d1 =', d1)
When running the program, the output is:
Delete items using clear() d = {} d1 = {} Delete items by allocation {} d = {} d1 = {1: 'one', 2: 'two'