89DEVs

Python: How to create an empty set?

How to create an empty set in Python?

To create an empty set in Python, use the {*()} or {*{}} or {*[]} operators. Or use the built-in function set() to create an empty set in Python.

create an empty set using operators

To create an empty set in Python, use the {*()} or {*{}} or {*[]} operators as shown below. # create an empty set using operators mySet1 = {*()} mySet2 = {*{}} mySet3 = {*[]} print(mySet1) print(mySet2) print(mySet3) In this example, three different empty sets are created by using different operators. Finally, all three sets are printed. set() set() set()

create an empty set using set() function

A second way of creating an empty set in Python is using the built-in set() function as shown below. # create an empty set using set() function mySet = set() print(mySet) The empty set is created and printed. set()

add elements to an empty set

To add elements to an empty set, use the add() method of Python sets as shown below. # add elements to an empty set mySet = set() mySet.add(1) mySet.add(2) mySet.add(3) print(mySet) In this code example, an empty set is created. Then three elements are added to the empty set one by one. Finally, the set is printed. {1, 2, 3} Remember, that elements in a set are unique. That means no duplicate elements are allowed. If an existing element is added using the add() method, it's just ignored and not added to the set. # add duplicate elements to an set mySet = set() mySet.add(1) mySet.add(1) mySet.add(1) print(mySet) In this case, integer 1 is added three times to the set. Because elements in sets are unique, only the first time the element is added. The following two calls to the add() method are ignored. Finally, the set is printed and it includes only one element. {1}

check if a set is empty

To check if a set is empty, use the not in operator. # check if set is empty mySet = set() if not mySet: True The set is empty and therefore considered False in Python. True is returned because the set is not True. True For an alternative way of checking if a set is empty, use the len() function. The len() function returns the length of the set, that is the number of elements in it. If the length returned is higher than 0, it indicates that the set is not empty. A third way of checking if a set is empty is by comparing the set to an empty set. The recommended way is the solution shown above, using the if not operator.

                
        

Summary


Click to jump to section