VOOZH about

URL: https://www.geeksforgeeks.org/python/frozenset-in-python/

⇱ frozenset() in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

frozenset() in Python

Last Updated : 18 Apr, 2026

The frozenset() function in Python creates an immutable set from an iterable. It stores only unique values and does not allow modification after creation. Since it is immutable, a frozenset can be used as a dictionary key or as an element of another set.

Example: In this example, a frozenset is created from a list:


Output
True
False

Explanation:

  • frozenset([...]) creates an immutable set and "cat" in 'a' checks membership.
  • Duplicate values (if any) are automatically removed.

Syntax 

frozenset(iterable)

  • Parameters: iterable - Any iterable object like list, tuple, set, string or dictionary.
  • Return Value: Returns a frozenset object.

Examples

Example 1: In this example, a frozenset is created and tried to modify it to show that it is immutable.

Output

frozenset({'banana', 'apple', 'orange'})
Traceback (most recent call last):
File "c:\Users\gfg0753\test.py", line 4, in <module>
f.add("grape")
^^^^^
AttributeError: 'frozenset' object has no attribute 'add'

Explanation:

  • frozenset([...]) creates an immutable set.
  • f.add() is not allowed because frozenset cannot be modified.

Example 2: In this example, a frozenset is created from a tuple and a list to see how duplicates are handled.


Output
frozenset()
frozenset({'Geeks', 'for'})

Explanation:

  • frozenset(a) creates an empty frozenset.
  • frozenset(b) removes duplicate "Geeks".

Example 3: Here, a dictionary is converted into a frozenset to observe what gets stored.


Output
frozenset({'name', 'age'})

Explanation: frozenset(d) stores only dictionary keys. Values are not included in the frozenset.

Frozenset operations

A frozenset supports common set operations such as union, intersection, difference and symmetric difference. Although it is immutable, these operations return new frozenset objects without modifying the original sets.


Output
frozenset({1, 2, 3, 4})
frozenset({1, 2, 3, 4, 5, 6})
frozenset({3, 4})
frozenset({1, 2})
frozenset({1, 2, 5, 6})

Explanation:

  • a.copy() creates a copy of a.
  • a.union(b) combines elements of both sets.
  • a.intersection(b) returns common elements.
  • a.difference(b) returns elements only in a.
  • a.symmetric_difference(b) returns elements that are not common to both sets.
Comment
Article Tags: