The Wayback Machine - https://web.archive.org/web/20240928070347/https://www.geeksforgeeks.org/python-dictionary-clear/
Open In App

Python Dictionary clear()

Last Updated : 13 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Syntax:

dict.clear()

Parameters:

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

Returns:

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

Parameters:

The clear() method take O(n) time.

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.

Python3




# Python program to demonstrate working of
# dictionary clear()
text = {1: "geeks", 2: "for"}
 
text.clear()
print('text =', text)


Output:

text = {}

How is it different from assigning {} to a dictionary? Please refer the below code to see the difference. When we assign {} to a dictionary, a new empty dictionary is created and assigned to the reference. But when we do clear on a dictionary reference, the actual dictionary content is removed, so all references referring to the dictionary become empty. 

Python3




# Python code to demonstrate difference
# 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)


Output:

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


Previous Article
Next Article

Similar Reads

PyQt5 – How to clear the content of label | clear and setText method
In this article, we will see how we can easily clear/erase the content of the label of PyQt5 application. This can be done in two ways - Using clear() method, this will clear the content of the label. Using setText() method with passing a blank string, this will update the content with blank string. Using clear() method - Syntax : label.clear() Arg
2 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Python Set clear() Method
Python Set clear() method removes all elements from the set. Python Set clear() Method Syntax: Syntax: set.clear() parameters: The clear() method doesn't take any parameters. Return: None Time complexity : The time complexity of set.clear() function on a set with n element is O(n) . Example 1: Python Set clear() Method Example C/C++ Code test_set =
2 min read
Matplotlib.axes.Axes.clear() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. matplotlib.axes.Axes.clear() Function The Axes.cle
1 min read
clear() element method - Selenium Python
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout - Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What
2 min read
Matplotlib.figure.Figure.clear() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. matplotlib.figure.Figure.clear() functi
1 min read
Clear LRU Cache in Python
The LRU is the Least Recently Used cache. LRU Cache is a type of high-speed memory, that is used to quicken the retrieval speed of frequently used data. It is implemented with the help of Queue and Hash data structures. Note: For more information, refer to Python – LRU Cache How can one interact with the LRU Cache in Python? Python's functool modul
2 min read
Python - turtle.clear()
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support. turtle.clear() This function is used to delete the turtle's drawings from the screen. Do not move state and position of the turtle as
2 min read
Must Know Things to Clear Your Python Coding Interview
Python is not only one of the most loved languages but rather it is used in various different domains. Due to its high dependency and usage in a lot of fields, there has suddenly been an increase in the job openings in Python programming language and related frameworks. Python developers are in high demand as it solves problems effortlessly in area
6 min read
Python List clear() Method
Python List clear() method removes all items from the List making it an empty/null list. Example C/C++ Code lis.clear() print(lis) Output[] What is List clear() Method?list clear() is an in-built function in Python, that is used to delete every element from a list. It can make any list into a null list and should be used with caution. It is one of
4 min read
Different ways to clear a list in Python
In this article, let's discuss different ways to clear a list in Python. Python provides a lot of different ways to clear a list and we will discuss them in this article. Example Input: [2, 3, 5, 6, 7]Output: []Explanation: Python list is cleared and it becomes empty so we have returned empty list.Different Ways to Remove from a List in PythonThere
5 min read
clear() method in PyQt5
While using PyQt5, there occur a need of removing or clearing labels in order to do so clear() method is used. This method belongs to the QLabel class, and can be used on only label widgets. Syntax : label.clear() Argument : It takes no argument. Action Performed : It clears(remove) the label from main window. Below is the implementation of this me
2 min read
How to clear Tkinter Canvas?
Tkinter is a Python Package for creating effective GUI applications. Tkinter's Canvas widget is nothing but a rectangular area that is used for drawing pictures, simple shapes, or any complex graph. We can place any widgets like text, button, or frames on the canvas. The task here is to generate a Python script that can clear Tkinter Canvas. For th
2 min read
How to Clear the Entry Widget After Button Press in Tkinter
The entry widget in Tkinter is a common input field that allows users to enter and edit a single line of text. Clearing the contents of this widget programmatically can enhance user interaction, especially after submitting or resetting a form. In this article, we will explore two different approaches to clear the entry after a button is pressed in
2 min read
How To Clear Out A Frame In The Tkinter?
Tkinter is a module in Python which is used to create GUI applications. It has many useful widgets such as Label, Button, Radiobutton, Checkbutton, Listbox, and more. Frame is a container in Tkinter within which many types of widgets and many numbers of widgets can be present. All the tkinter widgets such as buttons, Text, Label, Listbox, and more
2 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Print anagrams together in Python using List and Dictionary
Given an array of words, print all anagrams together. Examples: Input: arr = ['cat', 'dog', 'tac', 'god', 'act'] Output: 'cat tac act dog god' This problem has existing solution please refer Anagrams and Given a sequence of words, print all anagrams together links. We will solve this problem in python using List and Dictionary data structures. Appr
2 min read
Python dictionary, set and counter to check if frequencies can become same
Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make the frequency of each character same. Input : str =
2 min read
Find the first repeated word in a string in Python using Dictionary
Prerequisite : Dictionary data structure Given a string, Find the 1st repeated word in a string. Examples: Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he We have existing solution for this problem please refer Find the first repeated w
4 min read
Dictionary and counter in Python to find winner of election
Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name. Examples: Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny",
3 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Program to print all distinct elements of a given integer array in Python | Ordered Dictionary
Given an integer array, print all distinct elements in array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45} Output: 12, 10, 9, 45, 2 Input: arr[] = {1, 2, 3, 4, 5} Output: 1, 2, 3, 4, 5 Input: arr[] = {1, 1, 1, 1, 1}
2 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Python Dictionary to find mirror characters in a string
Given a string and a number N, we need to mirror the characters from the N-th position up to the length of the string in alphabetical order. In mirror operation, we change ‘a’ to ‘z’, ‘b’ to ‘y’, and so on. Examples: Input : N = 3 paradox Output : paizwlc We mirror characters from position 3 to end. Input : N = 6 pneumonia Output : pneumlmrz We hav
2 min read
Python Dictionary | Check if binary representations of two numbers are anagram
Given two numbers you are required to check whether they are anagrams of each other or not in binary representation. Examples: Input : a = 8, b = 4 Output : YesBinary representations of bothnumbers have same 0s and 1s.Input : a = 4, b = 5Output : NoCheck if binary representations of two numbersWe have existing solution for this problem please refer
3 min read
Python Dictionary copy()
Python Dictionary copy() method returns a shallow copy of the dictionary. let's see the Python Dictionary copy() method with examples: Examples Input: original = {1:'geeks', 2:'for'} new = original.copy() // Operation Output: original: {1: 'one', 2: 'two'} new: {1: 'one', 2: 'two'}Syntax of copy() method Syntax: dict.copy() Return: This method does
3 min read
Python dictionary values()
values() is an inbuilt method in Python programming language that returns a view object. The view object contains the values of the dictionary, as a list. If you use the type() method on the return value, you get "dict_values object". It must be cast to obtain the actual list. Python Dictionary values() Method Syntax Syntax: dictionary_name.values(
2 min read
How to use a List as a key of a Dictionary in Python 3?
In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained below . How does Python Dictionaries search their
3 min read
Counting the frequencies in a list using dictionary in Python
Given an unsorted list of some elements(which may or may not be integers), Find the frequency of each distinct element in the list using a Python dictionary. Example: Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] Output: 1 : 5 2 : 4 3 : 3 4 : 3 5 : 2 Explanation: Here 1 occurs 5 times, 2 occurs 4 times and so on... The problem can be s
4 min read
Python | Passing dictionary as keyword arguments
Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it's values as argument values. Let's d
3 min read
Article Tags :
Practice Tags :