YouTip LogoYouTip

Att Dictionary Clear

## Python Dictionary clear() Method In Python, dictionaries are mutable container objects that store data in key-value pairs. The `clear()` method is a built-in dictionary method used to remove all elements (keys and values) from a dictionary, leaving it completely empty. --- ## Description The `clear()` method empties a dictionary in place. Instead of creating a new empty dictionary, it modifies the existing dictionary object by deleting all of its key-value pairs. This is highly efficient and affects all references pointing to that specific dictionary. --- ## Syntax The syntax for the `clear()` method is straightforward: ```python dict.clear() ``` ### Parameters * **None**: The `clear()` method does not accept any parameters. ### Return Value * **None** (`None`): This method modifies the dictionary in place and does not return any value. --- ## Code Examples ### Basic Usage The following example demonstrates how to use the `clear()` method to empty a dictionary and verify its length before and after the operation. ```python # Initialize a dictionary with some data tinydict = {'Name': 'Zara', 'Age': 7} # Display the initial length of the dictionary print("Start Len : %d" % len(tinydict)) # Clear all elements from the dictionary tinydict.clear() # Display the length after clearing print("End Len : %d" % len(tinydict)) print("Dictionary content:", tinydict) ``` **Output:** ```text Start Len : 2 End Len : 0 Dictionary content: {} ``` --- ## Important Considerations ### `clear()` vs. Reassigning to `{}` It is important to understand the difference between calling `dict.clear()` and reassigning a dictionary variable to an empty dictionary `{}`. * **Reassignment (`dict = {}`)**: Creates a *new* empty dictionary object and assigns it to the variable. Any other variables referencing the original dictionary will remain unchanged. * **Clearing (`dict.clear()`)**: Empties the *existing* dictionary object in place. All variables referencing this dictionary will see the change. #### Example Comparison: ```python # Scenario 1: Reassigning to {} dict1 = {'a': 1, 'b': 2} dict2 = dict1 # dict2 references the same dictionary object dict1 = {} # dict1 now points to a new empty dictionary print("Scenario 1 - dict1:", dict1) # Output: {} print("Scenario 2 - dict2:", dict2) # Output: {'a': 1, 'b': 2} (Unchanged!) print("-" * 40) # Scenario 2: Using clear() dict1 = {'a': 1, 'b': 2} dict2 = dict1 # dict2 references the same dictionary object dict1.clear() # Empties the dictionary object in place print("Scenario 2 - dict1:", dict1) # Output: {} print("Scenario 2 - dict2:", dict2) # Output: {} (Cleared as well!) ```
← Att Dictionary CopyAtt Dictionary Type β†’