Machine Learning

Introduction to Python Set and Frozenset Methods

In this article, let’s have a look at some of the methods, related to Python’s implementation of sets. We will see what Python sets are, how to make them, when to utilize them, their built-in functions, their relationships and some simple examples.
A Set can be defined as an unordered list of data types that are iterable, changeable (mutable), and doesn’t have copy items. Python set class speaks the arithmetic notion of a set. Why do we use a set, rather than a list? Because these methods are highly optimized to verify whether a particular item is present in the set or not.
The frozen set is just an unchangeable category of a Python set object. In Python sets, you can change the items when you required, whereas items of the frozen set remain the same once created. Because of this, frozen sets are used as a key in Dictionary.
Here is the syntax of frozenset() method:
frozenset([iterable])
frozenset() Parameters
It uses a single parameter, as optional:

  • iterable – initiates the frozenset with.
  • Here Iterable refers to a set or dictionary or tuple, and more.

frozenset() for Dictionary
If you use a dictionary as an iterable for a frozen set, it only considers key of the dictionary for creating the set.
py1
#Output: The frozen set is: frozenset({‘name’, ‘sex’, ‘age’})
Return value from frozenset()
In frozenset() method, it returns an unchanged frozenset initiated with items from the provided iterable. On the off chance, if parameters not passed, then it returns an empty frozenset.
Since the sets don’t work on multiple occurrences for the same item, it has very useful sets for removing the duplicate values from a tuple/list that work on most math operations that are quite common like symmetric methods, unions and intersections.
Set Size
The lens() function is used to get the size of a set (the number of items).
py2
The set type is mutable (or simply a variable) — the contents can be altered using some simple functions like add() and remove().

  • Since it is mutable/variable, it will not have any hash value and can’t be used as either a dictionary key or as an item of another set.
  • If in-case the frozenset type is immutable (not a variable) and hashable — Then the contents cannot be changed once it’s created; anyway, it can be used as a dictionary key or as an item of another set.

Frozenset operations
As normal python sets work, frozenset also works on different methods like union, intersection, add, remove and more.
In order to create a Python set, we have to use either set() function or using { }. By using Python built-in function dir(), we return a list of all the attributes associated with a Python set. dir() function can be defined as a function that accepts a Python object as an argument and returns a list type that contains all attributes related to that object. Let’s have a glance on the attributes that are existed in Python sets.
py3
As shown in the above lines, some of the attributes have names starting and ending with double underscores (__). These attributes called as Magic Attributes and these are used internally in Python. Let’s not divert by discussing on attributes as of now.
Please have a note that, Python frozen sets don’t have all the functions that are specified in the above code, we have only a few of them i.e., – copy(), difference(), intersection(), isdisjoint(), clear(), remove(), issubset(), issuperset(), symmetric_difference(), union(), which work in the very same way they work in the event of Python sets. Thus, we focus more on Set methods here and learn them each of the one-by-one.
1. Set add() Method :
The set add () method adds a given item to a set. Here is the syntax –
set.add(item)
Note: If the element already exists, then it doesn’t add any item
Sample Code:
py4
2. clear() Method :
The name itself self-explanatory. The clear() method clears/removes all items from the set.
py5
3. copy() Method :
In this method it returns a shallow copy of that particular set. It is used to create a copy of the set.
py6
The major issue with copying is, if you want to modify the existing numbers set, automatically new_numbers set is also get modified. This is also known as a deep copy. In one line, copy() method modifies the given set and won’t return any value.
Here is the sample code:
py7
4. difference() Method :
The difference() method returns the difference of two sets. In this, if set A contains an argument, another set B, and returns a set that contains a combination of items that are existed in A but not present B.
Note: If no argument is given, then the empty set will be considered as an argument and the returns set A.
py8
py9
5. difference_update() Method :
Indeed, it’s quite fascinating to learn about this method. The difference_update() updates the set calling difference_update() method with the difference of sets.
If you use the difference()method, items of the sets A and B won’t change. But, if you use difference_update()method, then items of set A will change, assuming that, a method is called on set A. So, that set A contains the result, i.e., the difference between sets A and B. In arithmetic term, set A would be – A = A – B.
py10
6. discard() Method :
In this method, it deletes an argument item from the set if it exists, or else it returns nothing.
py11
Returns None, when that argument item doesn’t exist in the set..
py12
7. intersection() Method :
This intersection() method returns a new set of items that are common of all sets.
py13
Suppose if we have 3 sets A, B and C, and use intersection() method as A.intersection(B) or B.intersection(A).
py14
Note: If in-case no argument passed to intersection(), then it returns a shallow copy i.e., set (A).
8. intersection_update() Method :
In this intersection_update(), it updates the set calling of intersection_update() method with the help of intersection of sets.
Suppose if we have two sets A with set B as an argument, the output is the intersection of both the sets and it saves in the set on which method is called i.e. set A. Arithmetically we define this as: A = A & B.
Suppose if you take three sets the syntax will be
result = A.intersection_update(B, C)
If you run the code,

  • the result will be None
  • A will be equal to the intersection of A, and B
  • B remains immutable

py15
9. isdisjoint() Method :
In this isdisjoint() method, it returns True, if two sets have no comm0n items. If it has common items, then it returns False.
py16
For suppose, a set A is a ‘disjoint set‘ of another set B, if there are no common items in them then their intersection results in an empty set.
py17
10. issubset() Method :
In this issubset() method, it returns True if all items of a set are common in another set (when an argument passed). If no common items, then it returns False.
py18
For Example, when all the items of set A are present in set B, then we can say that set A is the subset of set B. It returns a boolean value True when the condition is true, or else returns False.
py19
11. issuperset() Method :
In this issuperset() method, if a set has all items that are present in another set, the it returns True or else, it returns False.
py20
For Suppose, all the items of set A are present in set B, then set B is the superset of set A. It returns a boolean value True when the condition is true, or else returns False.
py21
12. Set pop() Method :
In set.pop() method, it removes the first item from the set and returns the item that is removed. As Python sets are not ordered as a collection of data, it doesn’t contain any indices that related to set items, so we use pop() method.
Note: If the set is empty, it raises a KeyError exception.
py22
13. remove() Method :
In remove() method, it will search for the item passed to the argument in the set and removes it.
Using pop(), a random element is deleted from the set. We can also remove the specific item in the set by passing that to the argument to the remove()method.
Note: It doesn’t return any value.
Another keynote is item will be removed, only when it is present in the set, or else it will throw a KeyError exception.
Sample Code:
py23
14. symmetric_difference() Method :
In symmetric_difference(), it returns a new set that is not common in two sets i.e., symmetric difference of two sets (exactly opposite to Intersection).
py24
Suppose if we have two sets A and B, it returns a set of items that are not common to both sets. In Python, arithmetically we define this as: A ^ B.
py25
15. symmetric_difference_update() Method :
In symmetric_difference_update(), it returns difference of the two sets.
py26
If you take two sets A and set B as an argument, then the result will be the symmetric difference of both the sets will be calculated and stores in set A, whereas set B remains same.
py27
16. Set union() Method :
In the union() method, it returns a new set that contains distinct items from all the sets.
py28
For suppose, if we take three sets A, B and C as an argument, then returns a set that is the union of all the sets A, B and C.
Mathematically we represent this as: A | B | C.
py29
17. update() Method :
Using update(), you can add items from a set to the set.
Let’s take set A and another set B as arguments to this method, we get used A.update(B), then the output will be set A that contains added elements from the set B to A, whereas set B remains unchanged.
py30
Let’s windup this our discussion on Python Set and Frozenset methods for now. As already said to you, Python frozensets is a subset of the set of methods in relation with the Python sets. Frozenset methods work the same way as Sets work, so i haven’t covered them explicitly, so please consider this.
Please let us know about your inputs/feedback in the comment section beneath and stay tuned for more articles. Thank you.

Leave a Comment

Your email address will not be published.

You may also like

Crayon Yoda

Pin It on Pinterest