Python Method creates an immutable Set object from an iterable. It is a built-in Python function. As it is a set object, therefore, we cannot have duplicate values in the frozenset.
Example
In this example, we are creating a frozen set with the list in Python.
Python
animals = frozenset(["cat", "dog", "lion"])
print("cat" in animals)
print("elephant" in animals)
Output
True
False
Python frozenset() Syntax
Syntax : frozenset(iterable_object_name)
Parameter : iterable_object_name
- This function accepts iterable object as input parameter.
Return : Returns an equivalent frozenset object.
frozenset() in Python Examples
Working of Python frozenset()
In this example, we are showing how to create a frozen set in Python and we are showing that frozen set objects are immutable and can not be modified after the creation.
Python
fruits = frozenset(["apple", "banana", "orange"])
print(fruits)
fruits.add("cherry")
print(fruits)
Output
frozenset({'orange', 'apple', 'banana'})
ERROR!
Traceback (most recent call last):
File "<main.py>", line 3, in <module>
AttributeError: 'frozenset' object has no attribute 'add'Python frozenset for Tuple
If no parameters are passed to frozenset() function, then it returns an empty frozenset type object in Python.
Python
# passing an empty tuple
nu = ()
# converting tuple to frozenset
fnum = frozenset(nu)
# printing empty frozenset object
print("frozenset Object is : ", fnum)
Output
frozenset Object is : frozenset()
Python frozenset for List
Here as a parameter a list is passed and now its frozen set object is returned.
Python
l = ["Geeks", "for", "Geeks"]
# converting list to frozenset
fnum = frozenset(l)
# printing empty frozenset object
print("frozenset Object is : ", fnum)
Output
frozenset Object is : frozenset({'Geeks', 'for'})
frozenset in Python for Dictionary
Since frozen set objects are immutable, they are mainly used as keys in dictionary or elements of other sets. The below example explains it clearly.
Python
# creating a dictionary
Student = {"name": "Ankit", "age": 21, "sex": "Male",
"college": "MNNIT Allahabad", "address": "Allahabad"}
# making keys of dictionary as frozenset
key = frozenset(Student)
# printing dict keys as frozenset
print('The frozen set is:', key)
Output
The frozen set is: frozenset({'address', 'name', 'age', 'sex', 'college'})
Exceptions while using the frozenset() method in Python
If by mistake we want to change the frozen set object, then it throws a TypeError
Python
# creating a list
favourite_subject = ["OS", "DBMS", "Algo"]
# creating a frozenset
f_subject = frozenset(favourite_subject)
# below line will generate error
f_subject[1] = "Networking"
Output
TypeError Traceback (most recent call last)
Input In [13], in <cell line: 8>()
5 f_subject = frozenset(favourite_subject)
7 # below line will generate error
----> 8 f_subject[1] = "Networking"
TypeError: 'frozenset' object does not support item assignment
Frozenset operations
Frozen sets are immutable sets that allow you to perform various set operations such as union, intersection, difference, and symmetric difference.
Python
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
# copying a frozenset
C = A.copy()
print(C)
# union
union_set = A.union(B)
print(union_set)
# intersection
intersection_set = A.intersection(B)
print(intersection_set)
difference_set = A.difference(B)
print(difference_set)
# symmetric_difference
symmetric_difference_set = A.symmetric_difference(B)
print(symmetric_difference_set)
Output
frozenset({1, 2, 3, 4})
frozenset({1, 2, 3, 4, 5, 6})
frozenset({3, 4})
frozenset({1, 2})
frozenset({1, 2, 5, 6})frozenset() in Python – FAQs
Can we add elements to a frozenset?
No, you cannot add elements to a frozenset because it is immutable. Once created, a frozenset cannot be modified.
Example:
# Create a frozenset
frozen_set = frozenset([1, 2, 3])
# Attempt to add an element will raise an AttributeError
# frozen_set.add(4) # This will raise an AttributeError
Can we remove elements from a frozenset?
No, you cannot remove elements from a frozenset because it is immutable.
Example:
# Create a frozenset
frozen_set = frozenset([1, 2, 3])
# Attempt to remove an element will raise an AttributeError
# frozen_set.remove(2) # This will raise an AttributeError
How to convert a list to a frozenset?
You can convert a list to a frozenset by passing the list to the frozenset() constructor.
Example of Converting a List to a frozenset:
# List to frozenset
my_list = [1, 2, 3, 4, 5]
frozen_set = frozenset(my_list) # Convert list to frozenset
print(frozen_set) # Output: frozenset({1, 2, 3, 4, 5})
Can we convert a frozenset back to a set?
Yes, you can convert a frozenset back to a regular set using the set() constructor.
Example of Converting a frozenset to a Set:
# frozenset to set
frozen_set = frozenset([1, 2, 3, 4, 5])
my_set = set(frozen_set) # Convert frozenset back to a set
print(my_set) # Output: {1, 2, 3, 4, 5}
How to check if an element is in a frozenset?
You can check if an element is in a frozenset using the in keyword.
Example of Checking Membership:
# Create a frozenset
frozen_set = frozenset([1, 2, 3, 4, 5])
# Check if an element is in the frozenset
print(3 in frozen_set) # Output: True
print(6 in frozen_set) # Output: False
Similar Reads
Python Set Methods
A Set in Python is a collection of unique elements which are unordered and mutable. Python provides various functions to work with Set. In this article, we will see a list of all the functions provided by Python to deal with Sets. Adding and Removing elementsWe can add and remove elements form the s
2 min read
Set add() Method in Python
The Python set add() method adds a given element to a set if the element is not present in the set in Python. Example: Add Element to an Empty setIt is used to add a new element to the empty set. [GFGTABS] Python GEEK = set() GEEK.add('s') print("Letters are:", GEEK) # adding '
5 min read
Python Set clear() Method
Python Set clear() method removes all elements from the set. Python Set clear() Method Syntax: Syntax: set.clear() parameters: The clear() method doesn't take any parameters. Return: None Time complexity : The time complexity of set.clear() function on a set with n element is O(n) . Example 1: Pytho
2 min read
set copy() in python
The copy() method returns a shallow copy of the set in python. If we use "=" to copy a set to another set, when we modify in the copied set, the changes are also reflected in the original set. So we have to create a shallow copy of the set such that when we modify something in the copied set, change
2 min read
Python Set discard() Function
Python discard() is a built-in method to remove elements from the set. The discard() method takes exactly one argument. This method does not return any value. Example: In this example, we are removing the integer 3 from the set with discard() in Python. C/C++ Code my_set = {1, 2, 3, 4, 5} my_set.dis
3 min read
Python Set | difference_update()
The difference_update() method helps in an in-place way of differentiating the set. The previously discussed set difference() helps to find out the difference between two sets and returns a new set with the difference value, but the difference_update() updates the existing caller set.If A and B are
1 min read
Python Set | difference()
The difference between the two sets in Python is equal to the difference between the number of elements in two sets. The function difference() returns a set that is the difference between two sets. Let's try to find out what will be the difference between two sets A and B. Then (set A - set B) will
2 min read
issuperset() in Python
Python Set issuperset() method returns True if all elements of a set B are in set A. Then Set A is the superset of set B. Python issuperset() Method Syntax: Syntax: A.issuperset(B) Parameter: Any other Set to compare with Return: boolean value Python issuperset() exampleExample 1: Working of issubse
1 min read
Python Set issubset() Method
Python set issubset() method returns True if all elements of a set A are present in another set B which is passed as an argument, and returns False if all elements are not present in Python. Python Set issubset() Method SyntaxSyntax: set_obj.issubset(other_set) Parameter: other_set: any other set to
2 min read
Python Set isdisjoint() Method
Python set isdisjoint() function check whether the two sets are disjoint or not, if it is disjoint then it returns True otherwise it will return False. Two sets are said to be disjoint when their intersection is null. Python set isdisjoint() Method Syntax: Syntax: set1.isdisjoint(set2) Parameters: a
2 min read
Python Set - intersection_update() Method
Python intersection_update() method is used to update a set with common elements only of all the sets passed in parameter of intersection_update() method. Python set intersection_update() Method Syntax: Syntax: set.intersection_update(set1,set2,set3,...........,set n) Parameters: One or more sets Re
2 min read
Intersection() function Python
Python set intersection() method returns a new set with an element that is common to all set The intersection of two given sets is the largest set, which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements whi
2 min read
Find the length of a set in Python
In Python, a Set is a collection data type that is unordered and mutable. A set cannot have duplicate elements. Here, the task is to find out the number of elements present in a set. See the below examples. The idea is use len() in Python [GFGTABS] Python s1 = {1, 2, 3} print(len(s1)) s2 = {} print(
2 min read
Python Set pop() Method
Python set pop() removes any random element from the set and returns the removed element. In this article, we will see about the Python set pop() method. Example Input: {9, 1, 0} Output: {9, 1} Explanation: By using set pop() method, a random element 0 is removed from the set and remaining set is re
2 min read
Python | Remove items from Set
In this article, we will try to a way in which the elements can be removed from the set in a sequential manner. Before going into that let's learn various characteristics of a set. Examples Input : set([12, 10, 13, 15, 8, 9]) Output : {9, 10, 12, 13, 15} {10, 12, 13, 15} {12, 13, 15} {13, 15} {15} s
3 min read
Python Set | update()
Python update() function in set adds elements from a set (passed as an argument) to the set. If the element is present in both of the sets then the element comes only one time in the updated set. Python Set update() Method SyntaxSyntax : set1.update(set2) Here set1 is the set in which set2 will be a
3 min read
Union() function in Python
Python set Union() Method returns a new set that contains all the items from the original set. The union of two given sets is the set that contains all the elements of both sets. The union of two given sets A and B is a set that consists of all the elements of A and all the elements of B such that n
3 min read
Python set symmetric_difference_update()
The symmetric difference between the two sets is the set of elements that are in either of the sets but not in both of them. Symmetric Difference is marked in Green symmetric_difference() method returns a new set that contains a symmetric difference of two sets. The symmetric_difference_update() met
4 min read
Python Set symmetric_difference()
The symmetric difference of two sets set1 and set2 is the set of elements which are in either of the sets set1 or set2 but not in both. Syntax : set1_name.symmetric_difference(set2_name) Parameters : It only takes a single set as the parameter. If a list, tuple or dictionary is passed it converts it
1 min read
frozenset() in Python
Python Method creates an immutable Set object from an iterable. It is a built-in Python function. As it is a set object, therefore, we cannot have duplicate values in the frozenset. Example In this example, we are creating a frozen set with the list in Python. [GFGTABS] Python animals = frozenset([
4 min read