Python frozenset()
frozenset()
returns a frozen collection, and no elements can be added or removed from the frozen collection.
The downside of a frozenset is that once created it cannot be changed, there is no add()
, remove()
method.
Related course: Complete Python Programming Course & Exercises
syntax
frozenset()
parameters
- iterable: objects that can be iterated, such as lists, dictionaries, tuple groups, etc.
return value
- Returns a new frozenset object, which by default generates empty collections if no parameters are provided.
frozenset() example
The following examples demonstrate the use of frozenset().
>>>a = frozenset(range(10))
>>> a
frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = frozenset('germany')
>>> b
frozenset(['a', 'p', 'p', 'l', 'e'])
Example 2 The following example shows how to use the frozenset() function
print(frozenset()) #empty set, note {} this is an empty dictionary.
print(frozenset(range(0,8))) # Generate a new immutable set
a = frozenset('Hello')# to create an immutable set
print(a)
a.add('0') #Error
output
frozenset()
frozenset({0, 1, 2, 3, 4, 5, 6, 7})
frozenset({'H', 'o', 'l', 'e'})
Traceback (most recent call last):
File "frozenset.py", line 5, in <module>
a.add('0') #Error
AttributeError: 'frozenset' object has no attribute 'add'
Note that it's a colection, so it gets only the unique elements
>>> frozenset("good root mood")
frozenset({'r', 't', 'g', 'o', 'm', 'd', ' '})
>>> frozenset({1,1,1,1,1,2,2,2,3,3,3})
frozenset({1, 2, 3})
>>>