The frozenset() function returns frozenset object that cannot be modified. It contains an unordered collection of objects and it is unchangeable, so it can be used as a key in Dictionary.
frozenset([iterable]) #Where iterable can be a list, string, tuple, dictionary , set etc
The frozenset() function takes a single parameter. If the iterable argument is given, it returns a frozenset from it. The iterable contains elements to initialize the frozenset.
Parameter | Description | Required / Optional |
---|---|---|
iterable | Iterable can be set, dictionary, tuple, etc. | Optional |
no argument | empty frozenset object | Optional |
Return value is a immutable (cannot modify) frozen set of a given iterable.
Input | Return Value |
---|---|
Integer | An inetger frozen set |
character | A character frozen set |
No parameter | empty set |
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())
# frozensets are immutable
fSet.add('v')
Output:
The frozen set is: frozenset({'a', 'o', 'u', 'i', 'e'}) The empty frozen set is: frozenset() Traceback (most recent call last): File ", line 8, in fSet.add('v') AttributeError: 'frozenset' object has no attribute 'add'
fs = frozenset([1, 2, 3, 4, 5, 4, 3])
for x in fs:
print(x)
Output:
1 2 3 4 5
# random dictionary pers "John", "age": 23, "sex": "male"}
fSet = frozenset(person)
print('The frozen set is:', fSet)
Output:
The frozen set is: frozenset({'name', 'sex', 'age'})
# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
# copying a frozenset
C = A.copy() # Output: frozenset({1, 2, 3, 4})
print(C)
# union
print(A.union(B)) # Output: frozenset({1, 2, 3, 4, 5, 6})
# intersection
print(A.intersection(B)) # Output: frozenset({3, 4})
# difference
print(A.difference(B)) # Output: frozenset({1, 2})
# symmetric_difference
print(A.symmetric_difference(B)) # Output: frozenset({1, 2, 5, 6})
Output:
frozenset({1, 2, 3, 4}) frozenset({1, 2, 3, 4, 5, 6}) frozenset({3, 4}) frozenset({1, 2}) frozenset({1, 2, 5, 6})
# Frozensets
# initialize A, B and C
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
C = frozenset([5, 6])
# isdisjoint() method
print(A.isdisjoint(C)) # Output: True
# issubset() method
print(C.issubset(B)) # Output: True
# issuperset() method
print(B.issuperset(C)) # Output: True
Output:
True True True