Python set clear method

Python set clear function is one of the set methods used to clear or remove total set items. In this section, we discuss how to use this clear set function with practical examples.

The basic syntax behind this Python set clear function is as:

set_Name.clear()

Python set clear Example 1

The Python set clear function helps you to clear or remove the total number of items in a given set. The below code uses a set clear method to remove items from a clearSet (string set).

clearSet = {'apple', 'Mango', 'kiwi', 'orange', 'banana'}
print("\nOld Set Items = ", clearSet)

# Clear Set Items
clearSet.clear()
print("After Clear Method = ", clearSet)
Python set clear method 1

Python set clear example 2

clearIntSet = {15, 25, 35, 45, 55}
print("\nOld Set Items = ", clearIntSet)

# Clear Set Items
clearIntSet.clear()
print("After Clear Method = ", clearIntSet)
Old Set Items = {35, 45, 15, 55, 25}
After Clear Method = set()

TIP: Please refer to the Python set article to understand everything about Sets.

After executing this method, it returns an empty set = set().

# set clear

mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print("Old Set Items = ", mySet)

# Set clear()
mySet.clear()
print("New Set Items = ", mySet)

FruitSet = {'apple', 'Mango', 'orange', 'banana', 'cherry','kiwi'}
print("\nOld Set Items = ", FruitSet)

# Set clear()
FruitSet.clear()
print("New Set Items = ", FruitSet)
Old Set Items = {1, 2, 3, 4, 5, 6, 7, 8, 9}
New Set Items = set()

Old Set Items = {'cherry', 'kiwi', 'Mango', 'banana', 'apple', 'orange'}
New Set Items = set()