Javaexercise.com

Python frozenset() Method

Python frozenset() method is a built-in method. It returns a frozenset object from the given iterable. Itrerable can be a list, set, tuple etc. Frozenset is an immutable version of set that does not allow to change its elements.


Signature

frozenset([iterable])


Parameter Description
iterable (Optional) This single parameter can be a list, tuple, set etc.


Return Value

  If argument is given, it returns frozenset.

  If no argument is given, it returns empty set.


Python frozenset() Method Example

Let’s first understand, how this method works and what does it return?

# Creating a list
cities = ["Delhi","NewYork","Moscow"]
print(cities)
print("list type: ",type(cities))
# Applying frozenset() method
result = frozenset(cities)
print(result)
print("new type:",type(result))
Output
 ['Delhi', 'NewYork', 'Moscow']
 list type: < class 'list'>
 ['Delhi', 'NewYork', 'Moscow']
 new type: < class 'frozenset'>

See, in the above example, we created a list and applied frozenset() method. We checked type of list before and after applying method. See, the type of list is changed because the method frozenset() returns a frozenset object.


Python frozenset() Method Example

As we said, frozenset is immutable that means you can't modify it. It throws an error if you modify it. See, an example below.

# Creating a list
cities = ["Delhi","NewYork","Moscow"]
print(cities)
# Applying frozenset() method
result = frozenset(cities)
result[2] = "London"
print(cities)
Output

 TypeError: 'frozenset' object does not support item assignment