0
0
PythonHow-ToBeginner · 3 min read

How to Create frozenset in Python: Syntax and Examples

In Python, you create a frozenset by calling the frozenset() function with an iterable like a list or set. This creates an immutable set that cannot be changed after creation.
📐

Syntax

The syntax to create a frozenset is simple:

  • frozenset(iterable): Creates a frozenset from any iterable like list, set, tuple, or string.
  • If no argument is given, it creates an empty frozenset.
python
frozenset(iterable)
frozenset()
💻

Example

This example shows how to create a frozenset from a list and a set, and how it is immutable:

python
my_list = [1, 2, 3, 2]
frozen = frozenset(my_list)
print(frozen)

# Trying to add an element will cause an error
try:
    frozen.add(4)
except AttributeError as e:
    print(e)
Output
{1, 2, 3} 'frozenset' object has no attribute 'add'
⚠️

Common Pitfalls

Common mistakes when creating frozensets include:

  • Passing a non-iterable (like an integer) causes a TypeError.
  • Expecting to modify a frozenset after creation, but it is immutable.
  • Confusing frozenset() with set(), which is mutable.
python
wrong = 5

# This will raise an error because 5 is not iterable
try:
    fs = frozenset(wrong)
except TypeError as e:
    print(e)

# Correct way with an iterable
fs = frozenset([5])
print(fs)
Output
'int' object is not iterable frozenset({5})
📊

Quick Reference

UsageDescription
frozenset()Creates an empty frozenset
frozenset(iterable)Creates a frozenset from any iterable (list, set, tuple, string)
ImmutableCannot add or remove elements after creation
Useful as dict keysCan be used as keys in dictionaries because they are hashable

Key Takeaways

Use frozenset() with an iterable to create an immutable set in Python.
A frozenset cannot be changed after creation; it has no methods like add or remove.
Passing a non-iterable to frozenset() causes a TypeError.
Frozensets can be used as dictionary keys because they are hashable.
To create an empty frozenset, call frozenset() without arguments.