frozenset() Function in Python

Python frozenset() Function

The frozenset() function in Python is used to create an immutable frozenset object. A frozenset is an unordered collection of unique elements, similar to a set, but it cannot be modified once created. Frozensets are commonly used when you need an immutable set, such as for dictionary keys or elements in another set.

Here's the syntax for the frozenset() function:

frozenset(iterable)

The iterable argument is optional and can be any iterable object like a list, tuple, string, or another set. It contains the elements that will be included in the frozenset.

Here's an example that demonstrates the usage of frozenset():

numbers = [1, 2, 3, 4, 4, 5, 5]  # A list with duplicate elements
unique_numbers = frozenset(numbers)
print(unique_numbers)

Output:

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

In this example, the numbers list contains duplicate elements. By creating a frozenset from the list, the duplicates are automatically removed, and only the unique elements remain.

Since frozensets are immutable, you cannot modify them by adding or removing elements. However, you can perform various operations on frozensets, such as set operations (union, intersection, difference) or checking for membership using the in operator.

set1 = frozenset([1, 2, 3])
set2 = frozenset([2, 3, 4])

# Set operations
print(set1.union(set2))         # frozenset({1, 2, 3, 4})
print(set1.intersection(set2))  # frozenset({2, 3})
print(set1.difference(set2))    # frozenset({1})

# Membership check
print(2 in set1)  # True
print(4 in set1)  # False

Keep in mind that since frozensets are immutable, you cannot modify them directly. If you need a mutable set, you should use the regular set() function instead of frozenset().