Creating a set and checking if it is empty or not in python is simple and straightforward. In this article, we’ll look at how to create an empty set and the methods to check if set is empty in Python. Let’s first quickly go over what sets and when they are efficient and useful.
(If you already have the complete basics of sets, please feel free to skip the initial introductory sections and go to the creation of empty sets section.)
Set data type in Python
One of Python’s five built-in data types, called Set, is used to store collections of unique, unordered, mutable, and Iterable data.
- Unique: Set holds only unique elements in it by not allowing any duplicate Elements
- Unordered: Insertion order in sets is not preserved as the index of each new element will be calculated using a hash function.
- Mutable: We can add or remove set items, but we can’t access or update elements. Because set elements are not indexed like lists and tuples. As a result, you can’t access elements of the set using an index.
- Iterable: We can iterate through set elements in python.
Creating an empty Set in Python
a) Creating a set with elements
To create a set in python, we have to surround elements with curly braces { }.
social_media_sites = {'Facebook', 'Instagram', 'Twitter', 'Linkedin', 'Pinterest', 'Snapchat'}
print("social media sites:", social_media_sites)
Output:
social media sites: {'Instagram', 'Facebook', 'Linkedin', 'Pinterest', 'Snapchat', 'Twitter'}
But unlike lists and tuples, we can’t create empty sets using empty curly braces because it will be treated as a dictionary with empty key-value pairs.
empty_list = []
print(type(empty_list))
empty_tuple = ()
print(type(empty_tuple))
empty_dict = {}
print(type(empty_dict))
Output:
<class 'list'>
<class 'tuple'>
<class 'dict'>
We can create an empty set in python using the set() function.
set() function in python: It takes an iterable object as input and converts it into a set. If we don't pass anything to it, it will return an empty set.
b) Empty set creation
Now, Let’s see the code to create an empty set in python.
empty_set = set()
print(type(empty_set))
print(empty_set)
Output:
<class 'set'>
set()
Till now, we have seen the creation of an empty set. Now, let’s see how to check if a set is empty.
How to check if set is empty or not
There are 3 ways using which we can check if set is empty in python.
Method 1: Using len() function
In this method, we’ll get the length of a set using len() function. If its length is 0, the set is empty false otherwise.
def is_empty(set_in_python):
set_length = len(set_in_python)
if set_length == 0:
return True
else:
return False
empty_set = set()
non_empty_set = {1, 2, 3}
print("is set '", empty_set, "' empty?", is_empty_c(empty_set))
print("is set '", non_empty_set, "' empty?", is_empty_c(non_empty_set))
Output:
is set ' set() ' empty? True
is set ' {1, 2, 3} ' empty? False
Method 2: Using boolean context
The boolean context in python returns always True for non-empty collections and False for empty collections.
def is_empty(python_set):
# boolean context will be True for non-empty collection
if bool(python_set):
# returning False for is_empty as the collection is not empty
return False
else:
# return True for is_empty as the collection is empty
return True
empty_set = set()
non_empty_set = {1, 2, 3}
print("is set '", empty_set, "' empty?", is_empty_c(empty_set))
print("is set '", non_empty_set, "' empty?", is_empty_c(non_empty_set))
Output:
is set ' set() ' empty? True
is set ' {1, 2, 3} ' empty? False
Method 3: Comparing with another empty set
Here in this example, we’ll create one empty set and compare it with the given set. If both are equal, the set is empty false otherwise.
def is_empty(python_set):
empty_set = set()
if python_set == empty_set:
return True
else:
return False
empty_set = set()
non_empty_set = {1, 2, 3}
print("is set '", empty_set, "' empty?", is_empty_c(empty_set))
print("is set '", non_empty_set, "' empty?", is_empty_c(non_empty_set))
Output:
is set ' set() ' empty? True
is set ' {1, 2, 3} ' empty? False
Bottom Line
Though all the 3 methods are simple and easy to implement, we would recommend using the len() function, as it makes the code more readable than Using the boolean context as sometimes we get confused with its implementation.
Avoid creating another empty set as we did in Method 3 – Comparing with another empty set. This is not the standard way of checking if set is empty Python.
Note: We can get the length of sequence data types in constant time O(1) using the len() function whether its length is 10 or 10 million. The reason is they maintain a data member which holds the length of its data type and it will be altered when the element is added or removed. The len() function in python, just access this stored member to get the length.
More about Sets in Python
Till now we have seen how to create a set and how to check if it’s empty or not. In this section, let’s see a few of the important things to know about sets.
Sets are more efficient!
In programming, choosing the right data types that are more efficient is important. In the below scenarios, sets work more effectively than other built-in data types of python.
- To store unique elements in a collection.
- To do a membership test of an element in the collection using the ‘in’ operator.
- To do Mathematical operations like union, intersection, and difference.
Reason
Internally Sets are implemented using a hash table data structure that stores elements in an array. And each element in the array will be having a unique index named hashcode that is calculated by a hash function.
-> Checking the membership of an element is faster as we can get the element index using the hash function.
-> Inserting an element to a set regardless of its size is efficient and the time complexity is typically O(1) as they are implemented using hash tables.
Watch this video on hash tables to know more about them.
Set Operations:
Here We’ll discuss the main set operations such as union, intersection, difference, subset, and superset with examples.
For all the examples, we will use the below variables.
jack_amazon_cart = {'iPod', 'Smart tv', 'Spectacles', 't-shirt'}
jenny_amazon_cart = {'iPhone', 'Spectacles', 'Headphones', 'frock'}
a) Union
Returns all unique elements from both sets.
# Union Operation - Returns all unique elements from both sets
print("Union of ", jack_amazon_cart, " and ", jenny_amazon_cart, " is", end=" ")
print(jack_amazon_cart | jenny_amazon_cart)
Output:
Union of {'Smart tv', 'iPod', 'Spectacles', 't-shirt'} and {'iPhone', 'Headphones', 'Spectacles', 'frock'} is {'Headphones', 'iPod', 'Spectacles', 't-shirt', 'iPhone', 'Smart tv', 'frock'}
b) Intersection
Returns common elements from both sets.
# Intersection - Returns common elements from both sets
print("Intersection of ", jack_amazon_cart, " and ", jenny_amazon_cart, " is", end=" ")
print(jack_amazon_cart & jenny_amazon_cart)
Output:
Intersection of {'Smart tv', 'iPod', 'Spectacles', 't-shirt'} and {'iPhone', 'Headphones', 'Spectacles', 'frock'} is {'Spectacles'}
c) Difference
Returns elements that are in set one but not in set two.
# Difference - Returns elements that are in set 1 but not in set2
print("Difference between", jack_amazon_cart, " and ", jenny_amazon_cart, " is", end=" ")
print(jack_amazon_cart - jenny_amazon_cart)
Output:
Difference between {'Smart tv', 'iPod', 'Spectacles', 't-shirt'} and {'iPhone', 'Headphones', 'Spectacles', 'frock'} is {'Smart tv', 't-shirt', 'iPod'}
d) Subset
Returns True if set one is a subset of set two.
# Subset - Return True if first set is subset of second set false otherwise
print("Is", {'iPod', 'Smart tv', 'Spectacles'}, " subset of ", jenny_amazon_cart, " ?", end=" ")
print({'iPod', 'Smart tv', 'Spectacles'} <= jack_amazon_cart)
Output:
Is {'Smart tv', 'Spectacles', 'iPod'} subset of {'iPhone', 'Headphones', 'Spectacles', 'frock'} ? True
e) Superset
Returns True if set one contains all elements of set two.
# Superset - Returns True if the first set contains all elements from second set
print("Is ", {'iPod', 'Smart tv', 'Spectacles'}, " superset of ", jack_amazon_cart, " ?", end=" ")
print({'iPod', 'Smart tv', 'Spectacles'} >= jack_amazon_cart, end="\n\n")
print("Is ", {'iPod', 'Smart tv', 'Spectacles', 't-shirt', 'watch'}, " superset of ", jack_amazon_cart, " ?", end=" ")
print({'iPod', 'Smart tv', 'Spectacles', 't-shirt', 'watch'} >= jack_amazon_cart)
Output:
Is {'Smart tv', 'Spectacles', 'iPod'} superset of {'Smart tv', 'iPod', 'Spectacles', 't-shirt'} ? False
Is {'watch', 'iPod', 'Smart tv', 'Spectacles', 't-shirt'} superset of {'Smart tv', 'iPod', 'Spectacles', 't-shirt'} ? True
Set Methods:
We’ll use the below set as an example for all the methods.
code_threads_set = {'c', 'o', 'd', 'e', 't', 'h', 'r', 'e', 'a', 'd', 's'}
Method | Description |
add() | add elements to the set. Ex: code_threads_set.add(‘d’) |
remove() | removes the element and throws an error if the element does not exist. Ex: code_threads_set.remove(‘d’) |
clear() | remove all elements in the set. Ex: code_threads_set.clear() |
discard() | removes the element and won’t throw any error if the element does not exist. Ex: code_threads_set.discard(‘f’) |
pop() | removes a random element and returns it. Ex: code_threads_set.pop() |
copy() | returns the shallow copy of the set. Ex: dup = code_threads_set.copy() |
update() | update the set with the given iterable. Ex: code_threads_set.update([‘d’, ‘p’, ‘v’]) |
Frequently Asked Questions
-
How to check if set is empty?
We can check whether a set is empty or not by using the len() function. If the length of the set is 0, it is empty. For the other 2 methods, please visit this article.
-
How to create an empty set in Python?
We can create an empty set in python using set() function.
Ex: empty_set = set() -
Can we create an empty set with empty curly braces?
No, because it will create an empty dictionary instead of an empty set. To create an empty set, you have to use set() function.
-
Why in operator of set more efficient?
Internally sets are implemented using hash tables. So checking the membership of an element using in operator is very fast and efficient.
Hope we are able to help you to check if set is empty in Python using different ways. If you have any further queries, let us know through the comment box below. For more insightful articles, do follow codethreads.dev!