When working with data, you’ll frequently wish to save a list of data that cannot contain duplicate entries and whose values cannot be modified. For example, we want to provide a unique ID to each of the company’s employees, and there should not be any confusion between the employees functioning. This is where the Python set object comes into play. A set is an unordered collection of elements that can only have distinct values. This article will go through the fundamentals of Python sets and how to execute common operations on them, such as accessing, adding, updating, and removing values.
Python Set
A set is a group of elements that are not in any particular sequence i.e. elements are unordered. Every set element must be unique (no duplication) and immutable (cannot be changed). The set class in Python reflects the mathematical concept of a set. However, Python Sets are changeable, which means they can be changed after they are created.
Sets can also be utilized to conduct mathematical set operations such as union, intersection, and symmetric difference, among others.
We cannot use the indexing method to access items in sets as we can in lists because the Python sets are unordered.
Creating Python Sets
A set is formed by placing all of the objects (elements) inside curly braces {} and separating them with commas. The Python set() built-in function can also be used to generate a Python set. A set can contain any number of things, and the elements can be of many types, such as integers, strings, tuples, and so on. A set, on the other hand, does not allow mutable elements such as a list, dictionary, and so on.
Example 1
# Python program to create Sets
# creating a set of integers
my_set = {1, 2, 3, 4, 5}
print(my_set)
print(type(my_set))
# creating a set of mixed datatypes
my_set = {1, 'Python', 100.24, ('A', 'B', 'C')}
print(my_set)
Output
{1, 2, 3, 4, 5}
<class 'set'>
{100.24, 1, 'Python', ('A', 'B', 'C')}
Example 2
# Python program to create Sets
# set containing duplicate elements
my_set = {1, 2, 3, 4, 3, 2, 1}
print(my_set)
# creating a set using set() method
my_set = set(['Python', 'Java', 'C', 'C++'])
print(my_set)
# set cannot contain mutable items
# list is mutable
my_set = {2, 4, [3, 5, 7]}
print(my_set)
Output
{1, 2, 3, 4}
{'Python', 'C++', 'C', 'Java'}
Traceback (most recent call last):
 File "", line 12, in
TypeError: unhashable type: 'list'
Modifying a set in Python
Indexing or slicing cannot be used to access or update a set element. It is not supported by the Set data type. We can use the add() function to add a single element and the update() method to add several components. The update() method can take as arguments tuples, lists, strings, or other collections. Duplicates are avoided in all circumstances. Consider the following scenario.
# Python program to modify/add Set elements
my_set = {10, 20, 30}
print('Original Set:', my_set)
my_set.add(40)
print('Updated Set:', my_set)
my_set.update([50, 60, 70])
print('Updated Set:', my_set)
# using index for updation
# will throw TypeError
my_set[2] = 100
print(my_set)
Output
Original Set: {10, 20, 30}
Updated Set: {40, 10, 20, 30}
Updated Set: {70, 40, 10, 50, 20, 60, 30}
Traceback (most recent call last):
 File "", line 13, in
TypeError: 'set' object does not support item assignment
Removing elements from a set
Data elements from inside the Python set can be removed/deleted by using the discard() function and remove() function. If an item does not exist in a set, the discard() method removes it from the set and returns nothing. The remove() function will attempt to remove an item from a set and will raise an error if the item does not exist.
Example
# Python program to remove Set elements
my_set = {10, 20, 30, 40, 50}
print('Original Set:', my_set)
my_set.discard(30)
print('Updated Set:', my_set)
my_set.remove(40)
print('Updated Set:', my_set)
# discard element not present in set
my_set.discard(80)
print('Updated Set:', my_set)
# remove element not present in set
my_set.remove(80)
print('Updated Set:', my_set)
Output
Original Set: {40, 10, 50, 20, 30}
Updated Set: {40, 10, 50, 20}
Updated Set: {10, 50, 20}
Updated Set: {10, 50, 20}
Traceback (most recent call last):
 File "", line 16, in
KeyError: 80
Similarly, we can use the pop() method to remove and return an item. We can also use the clear() method to delete all of the elements from a set. Because the set is an unordered data type, it is impossible to predict which item will be popped. It is entirely random.
# Python program to remove Set elements
my_set = {2, 4, 6, 8, 10}
print('Original Set:', my_set)
my_set.pop()
print('Updated Set:', my_set)
my_set.clear()
print('Updated Set:', my_set)
Output
Original Set: {2, 4, 6, 8, 10}
Updated Set: {4, 6, 8, 10}
Updated Set: set()
Python Set Operations
Sets can be used to perform set operations such as union, intersection, difference, and symmetric difference. These set operations have no effect on the contents of a set. Instead, they run a calculation on an already existent set. This is something we can achieve using operators or procedures.
-
Set Union Operation
Union of 2 functions is the set of all the elements from both sets in a single different set. The | operator is used to perform union. The union() method can be used to do the same thing. If similar elements occur in both sets, then their single value is considered.
Example
# Python program to perform different set operations
# defining 2 sets
A = {1, 2, 3, 5, 7, 9}
B = {2, 4, 6, 7, 9, 0}
# set union operation
print('Union of A and B:', A | B)
Output
Union of A and B: {0, 1, 2, 3, 4, 5, 6, 7, 9}
-
Set Intersection Operation
The intersection of two sets is a set of elements that are shared by both sets i.e. generate a list of elements that are common between two sets. The & operator is used to perform intersection. The intersection() method can be used to do the same thing.
Example
# Python program to perform different set operations
# defining 2 sets
A = {1, 2, 3, 5, 7, 9}
B = {2, 4, 6, 7, 9, 0}
# set intersection operation
print('Intersection of A and B:', A & B)
Output
Intersection of A and B: {9, 2, 7}
-
Set Difference Operation
The difference between sets B and A (i.e. A-B) is a set of elements that are only in A but not in B. The – operator is used to perform a difference. The difference() method can be used to do the same thing. The difference() method can be used to determine which elements are present in one set but not in another.
Example
# Python program to perform different set operations
# defining 2 sets
A = {1, 2, 3, 5, 7, 9}
B = {2, 4, 6, 7, 9, 0}
# set difference operation
print('Difference of A and B:', A - B)
Output
Difference of A and B: {1, 3, 5}
-
Set Symmetric Difference Operation
A and B Symmetric Difference is a set of items in A and B but not in both (excluding the intersection). The operator is used to perform symmetric difference. The same thing can be done with the symmetric_difference() method.
Example
# Python program to perform different set operations
# defining 2 sets
A = {1, 2, 3, 5, 7, 9}
B = {2, 4, 6, 7, 9, 0}
# set symmetric difference operation
print('Symmetric Difference of A and B:', A ^ B)
Output
Symmetric Difference of A and B: {0, 1, 3, 4, 5, 6}
Other Python Set Methods
Just like Python string, list, and dictionary class methods, the set() function also has different methods that are used for performing various operations on the data elements. The following is a list of all the methods accessible with the set objects:
Method | Description |
Python frozenset() | Returns an immutable frozenset object |
Python Set add() | Adds elements to the set |
Python Set clear() | Deletes all the elements from the set |
Python Set copy() | Returns a copy of the set |
Python Set difference() | Returns the difference between 2 or more sets |
Python Set difference_update() | Updates the calling set by removing the items that are also included in the other specified sets |
Python Set discard() | Removes a specific element from the set |
Python Set intersection() | Returns an intersection of 2 or more sets |
Python Set intersection_update() | Updates the calling set by removing the items that are not present in the other specified sets |
Python Set isdisjoint() | Returns whether 2 sets have an intersection or not |
Python Set issubset() | Returns whether one set contains this set or not |
Python Set issuperset() | Returns whether this set contains another set or not |
Python Set pop() | Removes an arbitrary element |
Python Set remove() | Removes the specified element from the set |
Python Set symmetric_difference() | Returns symmetric differences of 2 or more sets |
Python Set symmetric_difference_update() | Updates the Set with symmetric difference |
Python Set union() | Returns union of sets |
Python Set update() | Adds elements to the set |
Other Set Operations
-
Set Membership Test
Using the in and not in keyword, we can determine whether or not an item exists in a set.
my_set = set('Programming')
print('z' in my_set)
print('r' in my_set)
print('b' not in my_set)
Output
False
True
True
-
Iterating Through a Set
To iterate through each element of the Python set, we use for loop.
for i in set('Python'):
   print(i)
Output
n
t
y
P
o
h
Built-in Functions with Set
Function | Description |
all() | Returns True if all the elements in the set are True |
any() | Returns True if any of the set’s elements are true. If the set is empty, the function returns False. |
enumerate() | This method returns an enumerate object. It stores the index and value for each item in the set as a pair. |
len() | Returns the no. of items in the set |
max() | Returns the largest element in the set |
min() | Returns the smallest element in the set |
sorted() | Returns a sorted list of elements in the set |
sum() | Returns the sum of all the elements in the set |
Python Frozenset
The frozen sets are the immutable version of the conventional sets, which means that the elements in the frozen set cannot be changed. Sets are mutable and unhashable, therefore they cannot be used as dictionary keys. Frozensets can be used as dictionary keys because they are hashable. The frozenset() function can be used to construct frozensets.
The elements of the frozen set cannot be modified once they have been created. We can’t update or add to the content of frozen sets with methods like add() or remove() (). Methods such as copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric difference(), and union() are available for this data type.
Example
A = frozenset([0, 1, 2, 3, 4])
B = frozenset([0, 2, 4, 6, 8])
print(A.isdisjoint(B))
print(A.difference(B))
print(A | B)
# error
print(A.add(3))
Output
False
frozenset({1, 3})
frozenset({0, 1, 2, 3, 4, 6, 8})
Traceback (most recent call last):
 File "", line 8, in
AttributeError: 'frozenset' object has no attribute 'add'
Frequently Asked Questions
Q1. What is set() in Python?
A set is a group of elements that are not in any particular sequence i.e. elements are unordered. Every set element must be unique (no duplication) and immutable (cannot be changed). The set class in Python reflects the mathematical concept of a set. However, Python Sets are changeable, which means they can be changed after they are created.
Sets can also be utilized to conduct mathematical set operations such as union, intersection, and symmetric difference, among others.
Q2. What is set and frozenset in Python?
- Python set – A set is formed by placing all of the objects (elements) inside curly braces {} and separating them with commas. The Python set() built-in function can also be used to generate a Python set. Python Sets are mutable, which means they can be changed after they are created.
- Python frozenset – The frozen sets are the immutable version of the conventional sets, which means that the elements in the frozen set cannot be changed. Sets are mutable and unhashable, therefore they cannot be used as dictionary keys. Frozensets can be used as dictionary keys because they are hashable. The frozenset() function can be used to construct frozensets.
Leave a Reply