Immutable Sets: Exploring Python’s frozenset() Function

Learn Python @ Freshers.in

Python’s frozenset() function provides a powerful tool for creating immutable sets, allowing developers to store unique and immutable collections of elements. In this article, we’ll delve into the syntax, usage, and practical examples of the frozenset() function to understand its significance in Python programming. The frozenset() function in Python provides a convenient way to create immutable sets, offering unique and hashable collections of elements.

Understanding the frozenset() Function:

The frozenset() function in Python is used to create immutable sets, which are similar to sets but cannot be modified after creation. This makes them suitable for scenarios where immutable and hashable collections are required.

1. Basic Usage:

# Basic usage of frozenset() function
numbers = [1, 2, 3, 4, 5]
frozen_numbers = frozenset(numbers)
print(frozen_numbers)

Output:

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

In this example, the frozenset() function creates an immutable set frozen_numbers from a list of numbers.

2. Handling Duplicate Elements:

# Handling duplicate elements
duplicates = [1, 2, 3, 3, 4, 5, 5]
frozen_duplicates = frozenset(duplicates)
print(frozen_duplicates)

Output:

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

The frozenset() function automatically removes duplicate elements, ensuring that the resulting set contains only unique values.

Properties of Immutable Sets:

1. Immutable Nature:

# Immutable nature of frozenset
frozen_set = frozenset([1, 2, 3])

try:
    frozen_set.add(4)
except AttributeError as e:
    print(e)

Output:

'frozenset' object has no attribute 'add'

Immutable sets created using frozenset() cannot be modified after creation, as demonstrated by the AttributeError when attempting to add an element.

2. Hashability:

# Hashability of frozenset
set1 = frozenset([1, 2, 3])
set2 = frozenset([2, 3, 1])
print(hash(set1) == hash(set2))

Output:

True

Immutable sets are hashable, meaning that sets with the same elements will have the same hash value.

Example: Unique Elements in a List

Let’s use frozenset() to find unique elements in a list:

# Finding unique elements using frozenset
data = [1, 2, 3, 3, 4, 5, 5]
unique_elements = frozenset(data)
print(unique_elements)

Output:

frozenset({1, 2, 3, 4, 5})
Author: user