Python set clear method

Python 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 function with practical examples.

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

set_Name.clear()

Python set clear Example

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

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

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

example 2

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

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

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

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

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

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

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

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

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