Table of Contents

Working with Sets

You can think of sets in python equivalent to sets in Mathematics. A set is created by placing all the items (elements) inside curly braces {}, separated by a comma. A set can store data in the form of a string literal, integer or any allowed data type in Python. You cannot access elements of the set using an index. Though, you can traverse a set using for loop. There are different methods or operations that can be performed on sets such as union, update, intersection, intersection_update, difference, difference_update, symmetric_difference, symmetric_difference_update, issubset, issuperset and lot more.

 

Initializing and Traversing a Set

In the below code, we will demonstrate, how to initialize a set and traverse the set using for loop.  Sets can be created using the function set().

Code: 
a = {1, 2, 3}

for i in a:
    print(i)

 

Output: 
1
2
3

How to add elements to a Set

Sets are mutable. But since they are unordered, indexing has no meaning.

We cannot access or change an element of a set using indexing or slicing. Sets does not support it.

We can add a single element using the add() method and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.

Code: 
a = {1, 2, 3}

for i in a:
    print(i)

a.add(4)
print(a)

#We are adding list as well as set to a set
#We are also trying to add duplicate element 1 to existing set
a.update([5, 6, 7], {1, 9, 10})
print(a)

 

Output: 
1
2
3
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 7, 9, 10}

Remove elements from a Set

A particular item can be removed from the set using methods, discard() and remove().

The only difference between the two is that, while using discard() if the item does not exist in the set, it remains unchanged. But remove() will raise an error in such condition.

Similarly, we can remove and return an item using the pop() method.

Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary.

We can also remove all items from a set using clear().

Code: 
a_set = {1, 2, 3, 4, 5, 6}
print(a_set)

a_set.discard(3)
print(a_set)

a_set.remove(5)
print(a_set)

a_set.pop()
print(a_set)

a_set.clear()
print(a_set)

 

Output: 
{1, 2, 3, 4, 5, 6}
{1, 2, 4, 5, 6}
{1, 2, 4, 6}
{2, 4, 6}
set()

Set Membership Test

We can test if an item exists in a set or not, using the keyword in

Code: 
a_set = {1, 2, 3, 4, 5, 6}

print(1 in a_set)
print(101 in a_set)

 

Output: 
True
False

 

Set Operations similar to Mathematics

Set Union operation

Union of two sets X and Y is a set of all unique elements from both sets.

A union is performed using | operator. The same can be accomplished using the method union().

Code: 
a_set = {1, 2, 3, 4, 5, 6}
b_set = {1, 7, 8, 9, 10}

c_set = a_set | b_set
print(c_set)

c_set = a_set.union(b_set)
print(c_set)

 

Output: 
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Set Intersection operation

The intersection of two sets X and Y is a set of elements that are common in both sets.

The intersection is performed using & operator. The same can be accomplished using the method intersection().

Code: 
a_set = {1, 2, 3, 4, 5, 6}
b_set = {1, 7, 8, 9, 10}

c_set = a_set & b_set
print(c_set)

c_set = a_set.intersection(b_set)
print(c_set)

 

Output: 
{1}
{1}

 

Set Difference operation

A difference of two sets X and Y refers to (X – Y) is a set of elements that are only in X but not in Y. Similarly, Y – X is a set of the element in Y but not in X.

The difference is performed using – minus operator. The same can be accomplished using the method difference().

Code: 
a_set = {1, 2, 3, 4, 5, 6}
b_set = {1, 7, 8, 9, 10}

c_set = a_set - b_set
print(c_set)

c_set = a_set.difference(b_set)
print(c_set)

d_set = b_set - a_set
print(d_set)

d_set = b_set.difference(a_set)
print(d_set)

 

Output: 
{2, 3, 4, 5, 6}
{2, 3, 4, 5, 6}
{8, 9, 10, 7}
{8, 9, 10, 7}

Set Symmetric Difference operation

Symmetric Difference of two sets X and Y is a set of elements in both X and Y except those that are common in both.

The symmetric difference is performed using ^ operator. The same can be accomplished using the method symmetric_difference().

Code: 
a_set = {1, 2, 3, 4, 5, 6}
b_set = {1, 7, 8, 9, 10}

c_set = a_set ^ b_set
print(c_set)

c_set = a_set.symmetric_difference(b_set)
print(c_set)

 

Output: 
{2, 3, 4, 5, 6, 7, 8, 9, 10}
{2, 3, 4, 5, 6, 7, 8, 9, 10}

Other Functions you can try

Function NameDescription
add()Adds an element to the set
copy()Returns a copy of the set
difference_update()Removes all elements of another set from this set
intersection_update()Updates the set with the intersection of itself and another
isdisjoint()Returns True if two sets have a null intersection
issubset()Returns True if another set contains this set
issuperset()Returns True if this set contains another set
symmetric_difference_update()Updates a set with the symmetric difference of itself and another

 

Built-in Functions with Set

 

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with set to perform different tasks.

Name of FunctionUsage
all()Return True if all elements of the set are true (or if the set is empty).
any()Return True if any element of the set is true. If the set is empty, return False.
enumerate()Return an enumerate object. It contains the index and value of all the items of set as a pair.
len()Return the length (the number of items) in the set.
max()Return the largest item in the set.
min()Return the smallest item in the set.
sorted()Return a new sorted list from elements in the set(does not sort the set itself).
sum()Return the sum of all elements in the set.
Code: 
a_set = {10, 3, 4, 0, 9, 123, -1, 3}


print(any(a_set))
print(all(a_set))
print(enumerate(a_set))
print(len(a_set))
print(max(a_set))
print(min(a_set))
print(sorted(a_set))
print(sum(a_set))

 

Output: 
True
False
<enumerate object at 0x000001C818F6F1D8>
7
123
-1
[-1, 0, 3, 4, 9, 10, 123]
148

Working with Frozenset

Set elements or values can be modified and changed. Sometimes, we need to use values that do not require modification or updation once assigned. Frozensets are immutable sets whose values cannot be changed once assigned. Sets being mutable are unhashable, so they can’t be used as dictionary keys. On the other hand, frozensets are hashable and can be used as keys to a dictionary.

Frozensets can be created using the function frozenset().

This datatype supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). Being immutable it does not have method that add or remove elements.

 

Code: 
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
X = frozenset([1, 2])

c = A.union(B)
print(c)

c = A.difference(B)
print(c)

c = A.intersection(B)
print(c)

c = A.isdisjoint(B)
print(c)

c = X.issubset(A)
print(c)

c = A.issuperset(X)
print(c)

c = A.union(B)
print(c)

 

Output: 
frozenset({1, 2, 3, 4, 5, 6})
frozenset({1, 2})
frozenset({3, 4})
False
True
True
frozenset({1, 2, 3, 4, 5, 6})