Skip to content

Python Set clear() | Method

  • by

Python Set clear() Method is used to remove all items from the set. All elements from the set will clear. And we will leave with an empty set.

set.clear() 

This method doesn’t take any parameters and doesn’t return any value.

Set clear in Python

Simple example code.

sno = {2, 3, 5, 7}
print(sno)

# clear all elements
sno.clear()

print(sno)
print(type(sno))

Output:

Python Set clear() Method

clear() Method with a String Set

# set of strings
names = {'John', 'Walter', 'Pink'}
print('Strings (before clear):', names)

# clear strings
names.clear()
print('Strings (after clear):', names)

If You Mean to Clear the Screen in the Console:

If you’re looking to clear the screen in a console application, you can use platform-specific solutions. Here’s an example using the os module, which works on many systems:

import os

# For Windows
if os.name == 'nt':
    os.system('cls')
# For Unix/Linux/MacOS
else:
    os.system('clear')

Note: the above code for clearing the console screen is platform-dependent.

Do comment if you have any doubts or suggestions on this Python set method topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *