Python frozenset() Function | immutable List, Tuple, Dictionary Examples

What is Python frozenset and frozenset() function?

Python frozenset is an immutable object and frozenset() method returns a frozenset object initialized with elements from the given iterable. The frozenset() is an inbuilt function in Python.

More about Frozen set: It’s just an immutable version of a Python set object. While elements of a set can be modify elements but frozen set remains the same after creation, you can’t change it.

It takes an iterable object as input and makes them immutable (unchangeable). Means elements of the frozen set remain the same after creation.

Syntax

Parameter Values

An iterable object, like list, set, tuple, dictionary etc.

Return value

It’s return an equivalent frozenset object.

Python frozenset() Function Examples

Let’s see how frozenset() works in Python with different types of iterable objects.

Using frozenset() Function in tuple

Example of creating a frozen set in python.

forzenset List

Output:

frozenset({‘orange’, ‘apple’, ‘banana’})

Making keys of a dictionary as frozenset

Output:

The frozen set is: frozenset({‘name’, ‘college’, ‘sex’, ‘age’, ‘address’})

Error: if try to change the value of a frozenset item.

Output:

Python frozense

frozenset order Python

frozensets, like sets, have no defined order

Q: What if you try to add or remove the item from frozen object?

Answer: It will throw and error.

Q: How to convert frozenset to normal sets or lists?

Answer: You can easily create list and tuple from frozenset object using built-in functions. see below example of frozenset to list and tuple:-

Output:

[1, 2, 3, 4, 5]
(1, 2, 3, 4, 5)

Iterating frozenset elements

Using for loop to iterate through frozen set elements.

Output:

1
2
3
4
5

Note: frozenset can also perform different operations like union, intersection, etc.

Do comment if you have any questions, doubts and suggestions on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.