frozenset() in Python

The frozenset() function in Python creates an immutable set from an iterable. Unlike regular sets, frozensets cannot be modified after creation, making them useful when you need a collection that should remain unchanged.

Syntax

frozenset(iterable)

Parameters:

  • iterable (optional): Any iterable object like list, tuple, string, or set. If no argument is provided, returns an empty frozenset.

Creating a Frozenset from a List

Here's how to convert a mutable list to an immutable frozenset ?

# Create a list
days = ["Mon", "Tue", "Wed", "Thu"]
print("Original list:", days)

# Convert to frozenset
frozen_days = frozenset(days)
print("Frozenset:", frozen_days)
print("Type:", type(frozen_days))
Original list: ['Mon', 'Tue', 'Wed', 'Thu']
Frozenset: frozenset({'Wed', 'Mon', 'Tue', 'Thu'})
Type: <class 'frozenset'>

Immutability Example

Once created, frozensets cannot be modified. Attempting to change elements will raise a TypeError ?

# Create frozenset
numbers = frozenset([1, 2, 3, 4, 5])
print("Frozenset:", numbers)

# Try to add an element (this will cause an error)
try:
    numbers.add(6)
except AttributeError as e:
    print("Error:", e)
Frozenset: frozenset({1, 2, 3, 4, 5})
Error: 'frozenset' object has no attribute 'add'

Creating from Different Iterables

Frozensets can be created from various iterable types ?

# From string
fs1 = frozenset("hello")
print("From string:", fs1)

# From tuple
fs2 = frozenset((1, 2, 3, 2, 1))
print("From tuple:", fs2)

# Empty frozenset
fs3 = frozenset()
print("Empty frozenset:", fs3)
From string: frozenset({'e', 'l', 'h', 'o'})
From tuple: frozenset({1, 2, 3})
Empty frozenset: frozenset()

Common Use Cases

Frozensets are useful as dictionary keys since they are hashable ?

# Using frozenset as dictionary key
skills_dict = {
    frozenset(['python', 'javascript']): 'Web Developer',
    frozenset(['java', 'spring']): 'Backend Developer',
    frozenset(['react', 'css']): 'Frontend Developer'
}

# Check if a skill combination exists
search_skills = frozenset(['python', 'javascript'])
if search_skills in skills_dict:
    print(f"Job role: {skills_dict[search_skills]}")
Job role: Web Developer

Set Operations with Frozensets

Frozensets support all set operations like union, intersection, and difference ?

fs1 = frozenset([1, 2, 3, 4])
fs2 = frozenset([3, 4, 5, 6])

print("Union:", fs1 | fs2)
print("Intersection:", fs1 & fs2)
print("Difference:", fs1 - fs2)
print("Symmetric difference:", fs1 ^ fs2)
Union: frozenset({1, 2, 3, 4, 5, 6})
Intersection: frozenset({3, 4})
Difference: frozenset({1, 2})
Symmetric difference: frozenset({1, 2, 5, 6})

Conclusion

Use frozenset() when you need an immutable set that can serve as dictionary keys or when you want to ensure data integrity. Frozensets support all set operations but cannot be modified after creation.

Updated on: 2026-03-15T19:09:14+05:30

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements