Python frozenset.add usage detailed explanation and examples

Python frozenset.add Usage Detailed Explanation and Examples

frozenset.add() Syntax

frozenset.add(x) is a method of the frozenset class that adds an element x to a frozenset. Because frozensets are immutable, existing frozensets cannot be modified directly; adding elements can only be done by creating a new frozenset.

Example 1: Add an element to a frozenset

# Create an empty frozenset
fs = frozenset()

# Use the add() method to add an element to a frozenset
fs = fs.add(1)

# Print the result
print(fs) # Output {1}

Example 2: Add multiple elements to a frozenset

# Create a frozenset with elements
fs = frozenset({1, 2, 3})

# Use the add() method to add an element to a frozenset
fs = fs.add(4)
fs = fs.add(5)

# Print the result
print(fs) # Output frozenset({1, 2, 3, 4, 5})

Example 3: Trying to modify frozenset elements (not possible)

# Create a frozenset with elements
fs = frozenset({1, 2, 3})

# Try using the add() method to modify elements in the frozenset
fs = fs.add(4)

# Print the result
print(fs) # Output AttributeError: 'frozenset' object has no attribute 'add'

Note that since frozenset is an immutable set, an AttributeError will be thrown when using the add() method. If you want to add elements, you need to convert the frozenset into a regular set and then use the set’s add() method to add elements.

Leave a Reply

Your email address will not be published. Required fields are marked *