Monday 29 November 2021

Python: frozenset: make the iterable immutable

‘frozenset’ function takes an iterable as argument and return an immutable one.

 

Syntax

frozenset(iterable_object_name)

 

Example

vowels = {'a', 'e', 'i', 'o', 'u'}
fset = frozenset(vowels)

frozenset_1.py

vowels = {'a', 'e', 'i', 'o', 'u'}
fset = frozenset(vowels)

print('vowels : ', vowels)
print('fset : ', fset)

Output

vowels : {'i', 'u', 'e', 'a', 'o'} fset : frozenset({'i', 'u', 'e', 'a', 'o'})

frozenset for a dictionary

When you pass a dictionary as an argument to frozenset, it construct the set using dictionary keys.

 

frozen_set_2.py

emp = {'id' : 1, 'name' : 'Krishna'}

fset = frozenset(emp)

print('emp : ', emp)
print('fset : ', fset)

Output

emp :  {'id': 1, 'name': 'Krishna'}
fset :  frozenset({'name', 'id'})

Since frozenset instances are immutable, you can’t perform any update and delete operations on a frozenset.

 

frozen_set_3.py

vowels = {'a', 'e', 'i', 'o', 'u'}
fset = frozenset(vowels)

print('vowels : ', vowels)
print('fset : ', fset)

vowels.remove('e')
print('vowels : ', vowels)

fset.remove('e')
print('fset : ', fset)

Output

vowels :  {'o', 'e', 'u', 'i', 'a'}
fset :  frozenset({'o', 'e', 'u', 'i', 'a'})
vowels :  {'o', 'u', 'i', 'a'}
Traceback (most recent call last):
  File "/Users/krishna/built-in-functions/frozen_set_3.py", line 10, in <module>
    fset.remove('e')
AttributeError: 'frozenset' object has no attribute 'remove'

Like normal sets, you can use frozenset while doing below operations.

 

a.   copy,

b.   difference,

c.    intersection,

d.   symmetric_difference, and

e.   union

 

frozen_set_4.py

evenNumbers={2, 4, 6, 8, 8, 4, 10}
oddNumbers={1, 3, 5, 7, 9}
powersOf2={1, 2, 4, 8, 16}

unionOfSets = evenNumbers|oddNumbers
intersectionOfSets = evenNumbers&powersOf2
differenceBetweenSets = evenNumbers-powersOf2
copyOfSet = evenNumbers.copy()

print("unionOfSets : ", unionOfSets)
print("intersectionOfSets : ", intersectionOfSets)
print("differenceBetweenSets : ", differenceBetweenSets)
print("copyOfSet : ", copyOfSet)

Output

unionOfSets :  {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
intersectionOfSets :  {8, 2, 4}
differenceBetweenSets :  {10, 6}
copyOfSet :  {2, 4, 6, 8, 10}


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment