Click for All Topics
frozenset()
function and pass any iterable element in this function.
Syntax –
frozenset(iterable)
Parameter –
Example –
s = [1,2,3,4,5]
fs = frozenset(s)
print("Frozen set:", fs)
print(type(fs))
# Output -
# Frozen set: frozenset({1, 2, 3, 4, 5})
#
Example 2 – Frozen set using a dictionary
d = {'firstname':'edSlash','lastname':'Services'}
frozen_set = frozenset(d)
print("Frozen set: ", frozen_set)
# Output -
# Frozen set: frozenset({'lastname', 'firstname'})
Let’s try to modify the frozen set –
f_set = frozenset('edSlash')
print("Frozen set: ", f_set)
print("\n\n")
f_Set.remove('s')
print(f_set)
# Output -
# Frozen set: frozenset({'a', 's', 'h', 'S', 'd', 'l', 'e'})
#Traceback (most recent call last):
# File "/home/main.py", line 4, in
# f_Set.remove('s')
#NameError: name 'f_Set' is not defined. Did you mean: 'f_set'?
Accessing elements of Frozen set –
l = [1,2,3,4,5,6]
f_set = frozenset(l)
print("Frozen set: ", f_set)
print("\n\nElements of frozen set: ")
for i in f_set:
print(i)
# Output -
# Frozen set: frozenset({1, 2, 3, 4, 5, 6})
# Elements of frozen set:
# 1
# 2
# 3
# 4
# 5
# 6
Operations on frozen set –
fs1 = frozenset('edSlash')
fs2 = frozenset('official')
print("Frozen set 1: ", fs1)
print("Frozen set 2: ", fs2)
print("\nNumber of elements in frozen set: ",len(fs1))
# Creating a copy of frozen set
fs1_copy = fs1.copy()
print("\nCopied frozen set:",fs1_copy)
# Union of two frozen sets
fs_union = fs1.union(fs2)
print("\nUnion set:",fs_union)
# Intersection of two frozen sets
fs_intersection = fs1.intersection(fs2)
print("\nIntersection set:",fs_intersection)
# Difference of two frozen sets
fs_difference = fs1.difference(fs2)
print("\nDifference set:",fs_difference)
# Symmetric difference of two frozen sets
fs_symmetric_difference = fs1.symmetric_difference(fs2)
print("\nSymmetric Difference set: ",fs_symmetric_difference)
# Output -
# Frozen set 1: frozenset({'e', 'h', 'S', 'd', 'a', 'l', 's'})
# Frozen set 2: frozenset({'o', 'a', 'i', 'c', 'l', 'f'})
# Number of elements in frozen set: 7
# Copied frozen set: frozenset({'e', 'h', 'S', 'd', 'a', 'l', 's'})
# Union set: frozenset({'o', 'e', 'h', 'S', 'd', 'a', 'i', 'c', 'l', 's', 'f'})
# Intersection set: frozenset({'l', 'a'})
# Difference set: frozenset({'e', 'h', 'S', 'd', 's'})
# Symmetric Difference set: frozenset({'i', 'f', 'o', 'e', 'h', 'S', 'd', 'c', 's'})
Frozen set | Set |
---|---|
It is immutable | It is mutable |
It is created using frozenset() function | It is created using {} curly braces or set() function. |
It is hashable | It is non hashable |
Supports operations that do not modify the frozen set | Supports operations that modify the original set |
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India