Python frozenset() Built in Function
Python frozenset() is a built-in function that returns an immutable set object. A set is a collection of unique and unordered elements that supports operations like union, intersection, difference, etc. A frozenset is like a set, but it cannot be modified or changed once created.
Here are some examples of how to use Python frozenset():
To create a frozenset from a list of fruits:
fruits = ["apple", "banana", "cherry"]
fset = frozenset(fruits)
print(fset)
Output:
frozenset({'apple', 'banana', 'cherry'})
To create an empty frozenset:
fset = frozenset()
print(fset)
Output:
frozenset()
To perform set operations with frozensets:
a = frozenset([1, 2, 3])
b = frozenset([3, 4, 5])
print(a.union(b)) # returns a new frozenset with elements from both a and b
print(a.intersection(b)) # returns a new frozenset with elements common to both a and b
print(a.difference(b)) # returns a new frozenset with elements in a but not in b
Output:
frozenset({1, 2, 3, 4, 5})
frozenset({3})
frozenset({1, 2})
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment