Python: Set and Frozenset

In programming terms, a set is a container containing non-repeating elements in random order.

A set in Python is an unordered collection of unique objects (ienon-repeating) of arbitrary types.

Sets in Python belong to mutable types. Elements are stored in an unsorted order and do not depend on when they are are added to the plural.

Python sets are used to solve problems in which has the value is only the element's membership in some set or its absence element in the plural. Working with sets in Python is similar to working with discrete sets in mathematics.

Creating Set

A set can be defined in different ways

Code: creating set

'''Creating empty set'''
a = set()
print(a)
# set() 


'''Creating a set from string characters'''
a = set('Python')
print(a) 
# {'n', 'o', 't', 'h', 'P', 'y'}


'''
An empty set cannot be created using a literal,
i.e. as like a = { }
will create not a set, but a dictionary.
But we can creating a set from one element:
a = {1, }
'''
a = {1,}
print(type(a), a)
# < class 'set' > {1}


'''Let's create the elements of the set manually'''
a = {'a', 'b', 'c'}
print(a)
# {'c', 'a', 'b'} 


'''Generating sets'''
a = {i*2 for i in range(5)}
print(a)
# {0, 2, 4, 6, 8}


'''Entering set elements from the keyboard with {}'''
a = {input('Enter a set element: ') for i in range(5)}
# Enter a set element: 1
# Enter a set element: 2
# Enter a set element: 3
# Enter a set element: 4
# Enter a set element: 5
print(a) 
# {'2', '1', '4', '5', '3'}


'''Entering set elements from the keyboard with set()'''
a = set(input('Enter a set element: ') for i in range(5))
# Enter a set element: 
# Enter a set element: 6
# Enter a set element: 7
# Enter a set element: 8
# Enter a set element: 9
print(a) 
# {'', '6', '7', '9', '8'}


'''
When creating sets, you need to take into account that
the elements in the set cannot be repeated.
If we create a set and add several to it
repeating elements, then each element will remain in one copy.
'''
a = set('programming')
print(a)
# {'n', 'o', 'i', 'g', 'r', 'm', 'a', 'p'}

Operations on Sets

Before discussing operations on sets, let's provide several definitions.

Definition 1: Equality of Sets

Sets are called equal if they consist of the same elements.

string index image

Definition 2: Subset (Belonging to a Set)

A set B is called a subset of a set A (belongs to set A) if and only if every element of set B is contained in set A.

string index image

Definition 3: Union of Sets

The union of sets A and B is a new set consisting of all elements of set A and set B, excluding duplicates.

string index image

Definition 4: Intersection of Sets

The intersection of two sets is a new set consisting of elements that belong to both the first and the second sets simultaneously.

string index image

Definition 5: Difference of Sets

The difference of two sets is a new set whose elements belong to the first set but do not belong to the second set.

string index image

Table of functions and methods that do not modify sets

Functions, Methods Description Example
len(a) Number of elements in the set (set size)
a = {1, 3, 5, 7, 8}
print(len(a))
Output:
5
n in a Checks if n belongs to set a. Returns True if it does, otherwise False
a = {1, 3, 5, 7, 8}
print(3 in a)
Output:
True
a == b Checks if sets a and b are equal.
a = {1, 3, 4}
b = {3, 1, 4}
print(a == b)
Output:
True
a.issubset(b) or a <= b Checks if all elements of set a are in set b. Returns True if a is a subset, otherwise False.
a = {1, 3, 4}
b = {3, 1}
print(b.issubset(a))
print(a >= b)
Output:
True
a.union(b, c, ...) or a | b | c | ... Union of multiple sets
a = {1, 3, 4}
b = {3, 1, 5}
print(a.union(b))
print(a | b)
Output:
{1, 3, 4, 5}
a.intersection(b, c, ...) or a & b & c & ... Intersection of multiple sets
a = {1, 3, 4}
b = {3, 1, 5}
print(a.intersection(b))
print(a & b)
Output:
{1, 3}
a.difference(b, c, ...) or a - b - c - ... Elements of set a not in any of the sets in parentheses. Subtraction from set a.
a = {1, 3}
b = {3, 1, 4, 5}
print(b.difference(a))
print(b - a)
Output:
{4, 5}
a.symmetric_difference(b) or a ^ b Elements belonging to only one of the sets a or b.
a = {1, 3, 0}
b = {3, 1, 4, 5}
print(b.symmetric_difference(a))
print(b ^ a)
Output:
{0, 4, 5}
b = a.copy() or b = a Creates a copy of set a.
a = {1, 3, 0}
b = a.copy()
c = a
print(b, end=' ')
print(c)
Output:
{0, 1, 3} {0, 1, 3}

Table of functions and methods that modify sets

Operator, Method Description Example
a.update(b, c, ...)
or
a |= b |= c |= ...
Union of sets, result is stored in the first set
a = {1, 3, 0}
b = {2, 5}
a.update(b)
print(a)
a = {1, 3, 0}
b = {2, 5}
a |= b
print(a)
# Output: {0, 1, 2, 3, 5}
a.intersection_update(b, c, ...)
or
a &= b &= c &= ...
Intersection of sets, result is stored in the first set
a = {1, 3, 2}
b = {2, 5}
a.intersection_update(b)
print(a)
a = {1, 3, 2}
b = {2, 5}
a &= b
print(a)
# Output: {2}
a.difference_update(b, c, ...)
or
a -= b -= c -= ...
Subtract sets from the first set, result is stored in the first set
a = {1, 3, 2}
b = {2, 5}
a.difference_update(b)
print(a)
a = {1, 3, 2}
b = {2, 5}
a -= b
print(a)
# Output: {1, 3}
a.symmetric_
difference_update(b)
or
a ^= b
Elements belonging to only one of the sets a or b, result is stored in set a
a = {1, 3, 2} b = {2, 5}
a.symmetric_difference_update(b)
print(a)
a = {1, 3, 2}
b = {2, 5}
a ^= b
print(a)
# Output: {1, 3, 5}
a.add(b) Adds element b to set a
a = {1, 3, 2}
a.add(5)
print(a)
# Output: {1, 2, 3, 5}
a.remove(b) Removes element b from set a. Raises KeyError if element is not present
a = {1, 3, 2}
a.remove(3)
print(a)
# Output: {1, 2}
a.discard(b) Removes element b from set a, does not raise error if element is not present
a = {1, 3, 2}
a.discard(3)
print(a)
# Output: {1, 2}
a.pop() Removes the first element from the set. As sets are unordered, the first element is unpredictable
a = {4, 3, 2}
a.pop()
print(a)
Output:{3, 4}
a.clear() Clears the set of all elements
a = {4, 3, 2}
a.clear()
print(a)
# Output: set()

Iterating over set elements

This method only allows you to output elements and then process them. Changing an element of a set in this way will not work.

Code: Iterating over set elements

a = {3, 5, 7, 2, 6}
for i in a:
    print(i, end=' ') 
# 2 3 5 6 7

Immutable Sets - Frozenset

Immutable sets, known as frozenset, are essentially the same as set, except that set is a mutable data type, while frozenset is an immutable data type. This is similar to the situation with lists and tuples, where lists are mutable data types, and tuples are immutable.

Immutable sets are created using the frozenset() function from any iterable object. Sets created from the same iterable object using set() and frozenset() will match in terms of content, but their data types will be different.

Code: Immutable Sets - Frozenset

a = set('Python')
b = frozenset('Python')
print(a == b)
print(type(a))
print(type(b)) 

# True
# < class 'set' >
# < class 'frozenset' >

All set set functions are defined over immutable sets frozenset, which do not directly change the set itself. If you try to add to created immutable set of any element, the result will be given error.

Links: Python documentation


[1] Python Set - methods


[2] Python Set - introduction to sets