Change language

Python dictionary clear ()

|

Syntax :

 dict.clear () 

Parameters :

 The clear ( ) method doesn’t take any parameters. 

Returns :

 The clear () method doesn’t return any value. 

Examples :

 Input: d = {1: "geeks", 2: "for"} d.clear () Output: d = { } 

Error :

 As we are not passing any parameters there is no chance for any error. 

# Python program to demonstrate how it works
# clear the dictionary ()

text = { 1 : " geeks " , 2 : "for" }

 
text.clear ()

print ( ’text =’ , text)

Output:

 text = {} 

How does it differ from assigning {} to a dictionary?
Please know Check out the code below to see the difference. When we assign {} to a dictionary, a new empty dictionary is created and assigned to the link. But when we clear the reference to the dictionary, the actual contents of the dictionary are removed, so all references to the dictionary are empty.

# Python code to show the differences
# clear and {}.

 

text1 = { 1 : "geeks" , 2 : "for" }

text2 = text1

 
# Using clear makes both text1 and text2
# empty
text1.clear ()

  

print ( ’After removing items using clear ()’ )

print ( ’text1 =’ , text1)

print ( ’text2 =’ , text2)

 

text1 = { 1 : "one" , 2 : " two " }

text2 = text1

 
# This makes only text1 empty.

text1 = {}

 

print ( ’After removing items by assigning {}’ )

print ( ’text1 =’ , text1)

print ( ’text2 =’ , text2)

Exit:

 After removing items using clear () text1 = {} text2 = {} After removing items by assigning {} text1 = {} text2 = {1: ’one’, 2:’ two’} 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method