Python frozenset.difference usage detailed explanation and examples
Python frozenset.difference Usage Detailed Explanation and Examples
frozenset.difference
returns the difference between two frozensets, that is, it returns the elements in the caller set that are not in the argument set. The syntax of this method is as follows:
frozenset.difference(*other)
*other
indicates that it accepts multiple arguments, each of which is a frozenset set.
Below are three examples:
Example 1:
set1 = frozenset([1, 2, 3, 4, 5])
set2 = frozenset([4, 5, 6, 7, 8])
result = set1.difference(set2)
print(result) # Output: frozenset({1, 2, 3})
In this example, set1
and set2
are two frozensets. By calling the set1.difference(set2)
method, the elements in set1
that are not in set2
are returned.
Example 2:
set1 = frozenset([1, 2, 3, 4, 5])
set2 = frozenset([1, 2, 3, 4, 5])
result = set1.difference(set2)
print(result) # Output: frozenset()
In this example, set1
and set2
are identical frozensets, and calling set1.difference(set2)
returns an empty set because the two sets have no difference.
Example 3:
set1 = frozenset([1, 2, 3])
result = set1.difference([2, 3, 4])
print(result) # Output: frozenset({1})
In this example, set1
is a frozenset set, and the argument is a list. Calling set1.difference([2, 3, 4])
returns the elements in set1
that are not in the argument list. Note that the argument can be any iterable object.
Summary: The frozenset.difference
method returns the difference between the caller set and the argument set, that is, it returns the elements that are in the caller set but not in the argument set.