How do you define an empty set in Python?

In Python, there are two ways to define an empty set.

Method 1: Use curly braces {} to define an empty set.

my_set = {}
print(my_set)  # 输出: {}
print(type(my_set))  # 输出: <class 'dict'>

It is important to note that an empty set defined using curly braces {} in Python is actually an empty dictionary, not an empty set. This can cause confusion because both empty sets and empty dictionaries are represented the same way in Python.

Option 2: Creating an empty set using the set() function.

my_set = set()
print(my_set)  # 输出: set()
print(type(my_set))  # 输出: <class 'set'>

By calling the set() function with no elements passed in, an empty set can be created. This method is clearer and more straightforward, so it is recommended to define an empty set this way.

bannerAds