0
0
Pythonprogramming~5 mins

Frozen set behavior in Python

Choose your learning style9 modes available
Introduction
A frozen set is like a regular set but cannot be changed after it is made. It helps keep data safe from accidental changes.
When you want a group of unique items that should not change.
When you need to use a set as a key in a dictionary.
When you want to share a set of items without risk of someone changing it.
When you want to make sure your data stays the same throughout the program.
Syntax
Python
frozenset(iterable)
The iterable can be a list, tuple, or another set.
Once created, you cannot add or remove items from a frozen set.
Examples
Create a frozen set from a list of numbers.
Python
fs = frozenset([1, 2, 3])
Create a frozen set from a set of strings.
Python
fs = frozenset({'apple', 'banana', 'cherry'})
Create an empty frozen set.
Python
fs = frozenset()
Sample Program
This program creates a frozen set from a list with repeated numbers. It prints the frozen set and then tries to add a new item, which causes an error because frozen sets cannot be changed.
Python
fs = frozenset([1, 2, 3, 2])
print(fs)

# Trying to add an item will cause an error
try:
    fs.add(4)
except AttributeError as e:
    print('Error:', e)
OutputSuccess
Important Notes
Frozen sets are immutable, meaning they cannot be changed after creation.
You can use frozen sets as keys in dictionaries because they are hashable.
Frozen sets support operations like union, intersection, and difference, just like regular sets.
Summary
Frozen sets are sets that cannot be changed after they are created.
They are useful when you want to protect data from being modified.
You create them using the frozenset() function with an iterable.