How to Create Empty Set in Python

0
61
How to Create Empty Set in Python

Starting your project with an empty data structure can help you perform better. Either you initialize an empty structure or check if it is empty. In this article, we will see how to create an empty set and how to check if it is empty.

What is Set in Python?

Python Set is an unordered collection that contains unique elements. A set can have multiple data types but cannot contain duplicate elements. Sets are immutable means after creating them, you cannot change them.

To create a set from a list in Python, use the set() method.

How to create an empty set in Python

To create an empty Set in Python, use the set() function and do not pass any arguments. Do not use empty curly braces {} because it will create an empty dictionary, not set.

empty_set = set()
print(empty_set)
print(type(empty_set))

Output

set()
<class 'set'>

We created an empty list and printed it in the console using the print() function. We also printed the data type using the type() function.

2 ways to check if a Set is empty in Python?

  1. Using the ifnot operator: The not-operator is used to reverse the false value.
  2. Using len(): If the len() function returns 0, the set is empty.

Using if-not operator

The not-operator can reverse the false value while using with if statement.

data_set = set()

if not data_set:
  print ("Set is empty")
else:
  print ("Set is not empty")

Output

Set is empty

If you assign values to the empty set, the above code’s else block will be executed.

data_set = set({11, 21})

if not data_set:
  print ("Set is empty")
else:
  print ("Set is not empty")

Output

Set is not empty

The declared set has two elements, which is why the set is not empty and executes the else block.

Using len() function

The len() is a built-in Python function that returns the length or size of the iterator. 

If you compare the result of len(set()) to 0 and if it returns True, then the set is empty otherwise not empty.

Use the double equals(==) operator to check equality in Python.

data_set = set()

if len(data_set) == 0:
  print ("Set is empty")
else:
  print ("Set is not empty")

Output

Set is empty

Similarly, if you assign values to an empty set, it won’t return 0 lengths; hence, it is not an empty set.

Conclusion

To create an empty set in Python, use the set() method and do not pass any arguments.

The best way to check if a set is empty, use the not operator.

That’s it.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.