Python Sets
Python Sets
A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable, and the sets remove the duplicate elements. Sets are mutable
which means we can modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the
set, i.e., we cannot directly access any element of the set by the index. However, we
can print them all together, or we can get the list of elements by looping through the
set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the
curly braces {}. Python also provides the set() method, which can be used to create the
set by the passed sequence.
Output:
Output:
It can contain any type of element such as integer, float, tuple etc. But mutable
elements (list, dictionary, set) can't be a member of set. Consider the following
example.
101.2K
Man Makes Shake Using Cashews And Figs Paste
Output:
<class 'set'>
Creating an empty set is a bit different because empty curly {} braces are also used to
create a dictionary as well. So Python provides the set() method used without an
argument to create an empty set.
Output:
<class 'dict'>
<class 'set'>
Let's see what happened if we provide the duplicate element to the set.
1. set5 = {1,2,4,4,5,8,9,9,10}
2. print("Return set with unique elements:",set5)
Output:
In the above code, we can see that set5 consisted of multiple duplicate elements when
we printed it remove the duplicity from the set.
Output:
To add more than one item in the set, Python provides the update() method. It
accepts iterable as an argument.
Output:
printing the original set ...
{'January', 'February', 'April', 'May', 'June', 'March'}
Output:
Output:
We can also use the pop() method to remove the item. Generally, the pop() method
will always remove the last item but the set is unordered, we can't determine which
element will be popped from set.
Consider the following example to remove the item from the set using pop() method.
Output:
In the above code, the last element of the Month set is March but the pop() method
removed the June and January because the set is unordered and the pop() method
could not determine the last element of the set.
Python provides the clear() method to remove all the items from the set.
Output:
If the key to be deleted from the set using discard() doesn't exist in the set, the Python
will not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't exist
in the set, the Python will raise an error.
Example-
Output:
Output:
Python also provides the union() method which can also be used to calculate the
union of two sets. Consider the following example.
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
Output:
{'Monday', 'Tuesday'}
Output:
{'Martin', 'David'}
Example 3:
1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
{1,2,5}
Output:
{'castle'}
Output:
{'Thursday', 'Wednesday'}
Output:
{'Thursday', 'Wednesday'}
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Set comparisons
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets
by using which we can check whether a set is a subset, superset, or equivalent to other
set. The boolean true or false is returned depending upon the items present inside the
sets.
Consider the following example.
FrozenSets
The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen
set cannot be changed and therefore it can be used as a key in the dictionary.
The elements of the frozen set cannot be changed after the creation. We cannot
change or append the content of the frozen sets by using the methods like add() or
remove().
The frozenset() method is used to create the frozenset object. The iterable sequence is
passed into this method which is converted into the frozen set as a return type of the
method.
1. Frozenset = frozenset([1,2,3,4,5])
2. print(type(Frozenset))
3. print("\nprinting the content of frozen set...")
4. for i in Frozenset:
5. print(i);
6. Frozenset.add(6) #gives an error since we cannot change the content of Froze
nset after creation
Output:
<class 'frozenset'>
Output:
<class 'dict'>
<class 'frozenset'>
Name
Country
ID
1. my_set = {1,2,3,4,5,6,12,24}
2. n = int(input("Enter the number you want to remove"))
3. my_set.discard(n)
4. print("After Removing:",my_set)
Output:
1. set1 = set([1,2,4,"John","CS"])
2. set1.update(["Apple","Mango","Grapes"])
3. print(set1)
Output:
Output:
1. set1 = {23,44,56,67,90,45,"Javatpoint"}
2. set2 = {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
{56, 23}
1. set1 = {23,44,56,67,90,45,"Javatpoint"}
2. set2 = {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
Above code raised an error because frozensets are immutable and can't be changed
after creation.
Example - 6: Write the program to find the issuperset, issubset and superset.
1. set1 = set(["Peter","James","Camroon","Ricky","Donald"])
2. set2 = set(["Camroon","Washington","Peter"])
3. set3 = set(["Peter"])
4.
5. issubset = set1 >= set2
6. print(issubset)
7. issuperset = set1 <= set2
8. print(issuperset)
9. issubset = set3 <= set2
10. print(issubset)
11. issuperset = set2 >= set3
12. print(issuperset)
Output:
False
False
True
True
SN Method Description
4 difference_update(....) It modifies this set by removing all the items that are
also present in the specified sets.
7 intersection_update(....) It removes the items from the original set that are not
present in both the sets (all the sets if more than one
are specified).