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

Python basic tutorial

Python flow control

Fonctions en Python

Types de données en 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 removes all items from the dictionary.

The syntax of clear() is:

dict.clear()

clear() parameters

clear() method without any parameters

clear() return value

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

Example1How does the clear() method work for dictionaries?

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'

Python dictionary methods