Python Set
Python Set

Python Set

Python Set is one of the four built-in Data Types available in Python used to store the collection of data. A Python set is an unordered collection of Python objects where each element in the set must be unique and immutable. It is used to store multiple items in a single variable.

How to create a Python set?

In Python, we can create a set using curly braces { }. To create a set, we place all the elements inside the curly braces. However, we cannot create an empty set using curly braces as in that case it will be considered as a dictionary. For example,

myset = {10, 20, 30, 40, 50}
print(type(myset))
print(myset)

#attempting to create an empty set
empty_set = {}
print("Type of {}:".format(empty_set), type(empty_set))

Output:

<class 'set'>
{50, 20, 40, 10, 30}
Type of {}: <class 'dict'>

In addition, Python has a built-in function set(). Using this function, we can create a set from elements of other collections (e.g., list, tuple, string, etc.). We can also initialize an empty set using this method. For example,

#creating a set from a list
set_from_list = set([5, 15, 25, 35])
print(type(set_from_list))
print("Set from list:", set_from_list)

#creating a set from a tuple
set_from_tuple = set(('abc', 'bcd', 'cde', 'def'))
print(type(set_from_tuple))
print("Set from tuple:", set_from_tuple)

#creating a set from a string
set_from_string = set("python")
print(type(set_from_string))
print("Set from string:", set_from_string)

#creating an empty set
empty_set = set()
print(type(empty_set))
print("Empty set:", empty_set)

Output:

<class 'set'>
Set from list: {25, 35, 5, 15}
<class 'set'>
Set from tuple: {'bcd', 'cde', 'def', 'abc'}
<class 'set'>
Set from string: {'h', 'n', 'p', 'o', 'y', 't'}
<class 'set'>
Empty set: set()

How to access elements of a Python set?

We cannot directly access elements of a set. Due to its unordered nature, we cannot access elements of a set by using an Index or a key. However, we can use Iteration to loop through the set elements and access all elements of the set. For example,

myset = {'pen', 'pencil', 'marker', 'sketch'}
print("Elements of the set:")
#accessing elements of the set
for element in myset:
    print(element)

Output:

Elements of the set:
pencil
marker
pen
sketch

How to add elements in a Python set?

We have two built-in methods add() and update() to add elements in a set. We will see each one of them.

add()

This method is used to add a single element to the set. We simply need to provide the element we want to insert into the set.

Syntaxset_name.add(element)

cars = {'ferrari', 'ford', 'jaguar', 'jeep'}
print("Initial set:", cars)

#adding new car to the set
cars.add('tesla')
print("New set:", cars)

Output:

Initial set: {'jaguar', 'jeep', 'ford', 'ferrari'}
New set: {'tesla', 'ferrari', 'jeep', 'jaguar', 'ford'}

update()

This method is used to add multiple elements to the set. This method accepts an iterable as its argument and adds all the elements of that iterable to the set. The iterable can be a python list, tuple, dictionary or it could be another set.

Syntax – set_name.update(iterable)

cars = {'ferrari', 'ford', 'jaguar'}
print("Initial set:", cars)

#adding new cars to the set
cars.update(['toyota', 'mustang', 'hummer'])
print("New set:", cars)

Output:

Initial set: {'jaguar', 'ford', 'ferrari'}
New set: {'hummer', 'mustang', 'toyota', 'ferrari', 'ford', 'jaguar'}

How to remove elements from a Python set?

We have three options to remove elements from a set. Let’s see each one of them.

Removing a specific element

To remove a specific element we have two built-in methods remove() and discard() in Python. Both these methods remove the specified element from the set. These methods are almost similar. The only difference between them is that if the element we want to remove is not present in the set then the remove() method will raise an exception (KeyError) whereas the discard() method will not raise any error.

metals = {'gold', 'iron', 'silver', 'copper', 'steel'}
print("Initial set:", metals)

#removing an element using remove() method
metals.remove('copper')
print("Set after removing 'copper':", metals)

#removing an element using discard() method
metals.discard('silver')
print("Set aftre removing 'silver':", metals)

Output:

Initial set: {'steel', 'copper', 'gold', 'iron', 'silver'}
Set after removing 'copper': {'steel', 'gold', 'iron', 'silver'}
Set aftre removing 'silver': {'steel', 'gold', 'iron'}

Removing an arbitrary element

To remove an arbitrary element we have built-in method pop(). This method removes a random element from the set and returns that element. However, we don’t use this method much frequently due to its fewer applications.

metals = {'gold', 'iron', 'silver', 'copper', 'steel'}
print("Initial set:", metals)

#removing an arbitrary element using pop() method
removed_element = metals.pop()
print("Element removed:", removed_element)
print("Set after removing the element:", metals)

Output:

Initial set: {'gold', 'iron', 'silver', 'copper', 'steel'}
Element removed: gold
Set after removing the element: {'iron', 'silver', 'copper', 'steel'}

Removing all elements from the set

We can remove all the elements of the set using clear() method. It empties the set by removing all elements at once. For example,

metals = {'gold', 'iron', 'silver', 'copper', 'steel'}
print("Initial set:", metals)

#removing all elements from set
metals.clear()
print("Set after removing all elements:", metals)

Output:

Initial set: {'gold', 'silver', 'iron', 'steel', 'copper'}
Set after removing all elements: set()

Properties of a Python set

Mutability

Python sets are partially Mutable. We can add or remove elements from a set but we cannot modify an existing element. However, elements of the set must be immutable. Therefore, we cannot have Lists or dictionaries as elements of a set. We have already seen several methods to add and remove elements in a set.

Unordered Sequence

As we already discussed Set is an unordered sequence. That means the elements in a set do not have a defined order. Elements can appear in a different order every time we print or access a set. That’s also a reason why the set does not support Indexing.

Duplicates

Sets do not support duplicate elements. Since a set is a collection of distinct elements, we cannot have two same values in a set.

Data types of set elements

A set can contain different elements where the data type of each element may be different. However, an element cannot be of any mutable data type e.g., list or dictionary. For example,

myset = {35, 'python', 19.35, True, (1, 2, 3)}
print(type(myset))
print(myset)

#creating a set with a mutable element
print("\nAttempt to create a list with mutable object giving error:")
try:
    invalid_set = {2, [1, 2, 3], 'python'}
except Exception as e:
    print(type(e), e)

Output:

<class 'set'>
{True, 35, 19.35, 'python', (1, 2, 3)}

Attempt to create a list with mutable object giving error:
<class 'TypeError'> unhashable type: 'list'

Length of the set

The length of a set refers to the number of elements present in it. We can determine the length of the set using the len() method. For example,

weekdays = {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'}
print("Length of set:", len(weekdays))

Output:

Length of set: 7

What are set operations in Python?

A. Union

Union operation determines the union of two sets. The union of two sets will contain all items that are present in both sets. In this case, duplicate items (items that are common in both sets) will only be considered once. Union operation can be carried out using bitwise OR (|) operator as well as using built-in method union(). For example,

set1 = {'January', 'February', 'March', 'April'}
set2 = {'February', 'April', 'May', 'June'}

#union using OR operator
print("Using operator:-")
union1 = set1 | set2
print("Union of set1 and set2:", union1)

#union using union() method
print("Using method:-")
union2 = set1.union(set2)
print("Union of set1 and set2:", union2)

Output:

Using operator:-
Union of set1 and set2: {'May', 'April', 'January', 'March', 'February', 'June'}
Using method:-
Union of set1 and set2: {'May', 'April', 'January', 'March', 'February', 'June'}

B. Intersection

Intersection operation determines the intersection of two sets. The intersection of two sets will give a set of elements that are common in both sets. Intersection operation can be carried out using bitwise AND (&) operator as well as using built-in method intersection(). For example,

set1 = {'January', 'February', 'March', 'April'}
set2 = {'February', 'April', 'May', 'June'}

#intersection using AND operator
print("Using operator:-")
intersection1 = set1 & set2
print("Intersection of set1 and set2:", intersection1)

#intersection using intersection() method
print("Using method:-")
intersection2 = set1.intersection(set2)
print("Intersection of set1 and set2:", intersection2)

Output:

Using operator:-
Intersection of set1 and set2: {'February', 'April'}
Using method:-
Intersection of set1 and set2: {'February', 'April'}

C. Difference

Difference operation determines the difference of two sets. Suppose we have two sets A and B. The difference of the two sets (A – B) is a set of elements that are present only in A but not B. Difference operation can be performed using subtraction (-) operator as well as using built-in method difference(). For example,

A = {'January', 'February', 'March', 'April'}
B = {'February', 'April', 'May', 'June'}

#difference using Subtraction operator
print("Using operator:-")
difference1 = A - B
print("A - B =", difference1)

#difference using difference() method
print("Using method:-")
difference2 = B.difference(A)
print("B - A =", difference2)

Output:

Using operator:-
A - B = {'March', 'January'}
Using method:-
B - A = {'May', 'June'}

D. Symmetric Difference

Symmetric operation determines the symmetric difference of two sets. The symmetric difference of two sets is a set containing all the elements of both sets excluding those which are common in both sets. In other words, it is the union of two sets excluding the intersection. Symmetric difference operation can be performed using bitwise XOR (^) operator as well as using built-in method symmetric_difference(). For example,

A = {'January', 'February', 'March', 'April'}
B = {'February', 'April', 'May', 'June'}

#symmetric difference using XOR operator
print("Using operator:-")
symm_diff1 = A ^ B
print("Symmetric difference of A and B:", symm_diff1)

#symmetric difference using symmetric_difference() method
print("Using method:-")
symm_diff2 = A.symmetric_difference(B)
print("Symmetric difference of A and B:", symm_diff2)

Output:

Using operator:-
Symmetric difference of A and B: {'January', 'May', 'June', 'March'}
Using method:-
Symmetric difference of A and B: {'January', 'May', 'June', 'March'}

What are Frozen sets?

Frozen sets are the immutable form of Python sets just like a python tuple, which is an immutable form of a list. These sets cannot be changed once defined. That means we cannot add or remove elements from the frozen sets. We use frozen sets when we want to use an immutable set.

Frozen sets can be created using frozenset() method. We simply need to pass an iterable to this method and it will create a frozen set using its elements. For example,

Frozen_set = frozenset({10, 20, 30, 40, 50})
print(type(Frozen_set))
print(Frozen_set)

Output:

<class 'frozenset'>
frozenset({50, 20, 40, 10, 30})

Python Set methods

MethodDescription
add(element)As we have already discussed this method adds the specified element in the set
clear()As we have already discussed this method removes all the elements of the set
copy()This method returns the copy of the set
difference()As we have already discussed this method is used to find the difference of two sets
difference_update()This method updates the set to the new set that we get as a result of difference operation
discard(element)As we have already discussed this method removes the specified element from the set
intersection()As we have already discussed this method is used to find the intersection of two sets
intersection_update()This method updates the set to the new set that we get as a result of intersection of two sets
isdisjoint()This method checks whether the intersection of two sets is an empty set and return a boolean value
issubset()This method checks whether the specified set is a subset of this set
issuperset()This method checks whether the specified set is a superset of this set
pop()As we have already discussed this method removes an arbitrary element from the set
remove(element)As we have already discussed this method removes the specified element from the set
symmetric_difference()As we have already discussed this method is used to find the symmetric difference of two sets
symmetric_difference_update()This method updates the set to the new set that we get as a result of the symmetric difference operation
union()As we have already discussed this method is used to find the union of two sets
update(iterable)As we have already discussed this method updates the set with all the elements of specified iterable

Conclusion

In this article we have read about creating a Python set, adding and removing its elements. We have also read about the important properties of Python sets and set operations. In the end, we have discussed about Frozen sets and various built-in set methods.

Donate to Avid Python

Dear reader,
If you found this article helpful and informative, I would greatly appreciate your support in keeping this blog running by making a donation. Your contributions help us continue creating valuable content for you and others who come across my blog. 
No matter how big or small, every donation is a way of saying "thank you" and shows that you value the time and effort we put into writing these articles. If you feel that our article has provided value to you, We would be grateful for any amount you choose to donate. 
Thank you for your support! 
Best regards, 
Aditya
Founder

If you want to Pay Using UPI, you can also scan the following QR code.

Payment QR Code
Payment QR Code

Piyush Sharma

Third-year computer engineering student inclined towards the latest trends and technology. Always keen to explore and ready to learn new things. To read more articles on Python, stay tuned to avidpython.com.

Leave a Reply