English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Função do Python

Tipos de Dados do Python

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python dictionary clear() usage and example

Python dictionary methods

The clear() method deletes all items from the dictionary.

The syntax of clear() is:

dict.clear()

clear() parameters

clear() without any parameters

clear() return value

The clear() method does not return any value (returns None).

Example1How does the clear() method work on the dictionary?

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'

Python dictionary methods