frozenset() : creates an immutable version of a set

fronzenset(my_iterable)
my_iterable : This is an iterable object like List, tuple, set Output is unchangeable frozenset object. This object is immutable ( what is immutable ? )

Using List
my_list=[1,2,3]
my_list=frozenset(my_list)
print(my_list) # frozenset({1, 2, 3})
We will try to change one element
my_list=[1,2,3]
my_list=frozenset(my_list)
my_list[1]=8
print(my_list) # frozenset({1, 2, 3})
Above code will generate error saying
TypeError: 'frozenset' object does not support item assignment

Using tuple
my_tuple=(1,2,3)
my_tuple=frozenset(my_tuple)
my_tuple[1]=5
Above code will generate error saying
TypeError: 'frozenset' object does not support item assignment

One more example
my_tuple=(1,2,3)
my_tuple +=(4,5)
print(my_tuple)
my_tuple=frozenset(my_tuple)
my_tuple +=(6,7)
Above code will generate error saying
TypeError: unsupported operand type(s) for +=: 'frozenset' and 'tuple'

Use Cases for frozenset()

  • As Dictionary Keys: Since frozensets are immutable and hashable, they can be used as keys in dictionaries, unlike regular sets.
  • As Elements in Sets: Frozensets can be elements of other sets because they are hashable, while regular sets cannot.
  • Data Integrity: When we need to ensure that a collection of items remains unchanged throughout the lifetime of a program, frozensets are a useful tool.
In summary, frozenset() is a built-in Python function used to create immutable and hashable sets. It is particularly useful when you need a collection of unique elements that should not change over time, or when you require a set-like object to be used as a dictionary key or a set element.

Python


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer