'Equality between frozensets
Example:
>>> tuple((1, 2)) == tuple((2, 1))
False
>>> frozenset((1, 2)) == frozenset((2, 1))
True
Frozen sets are immutable. I would expect that equality between immutable objects should by determined by order, but here obviously that is not the case.
How can I discard frozensets with same elements and different order, without casting to different type?
Solution 1:[1]
The short answer is you can't, since as pointed out in the comments, sets and frozensets are unordered data structures. Here are some excerpts from the docs* to support this statement:
A set object is an unordered collection of distinct hashable objects.
There are currently two built-in set types,
setandfrozenset. Thesettype is mutable — the contents can be changed using methods likeadd()andremove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. Thefrozensettype is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.
* Python 2.7.12
For a better grasp of the equality issue, I would encourage you to run the following snippet using the Online Python Tutor:
tup_1 = tuple((1, 2))
tup_2 = tuple((2, 1))
fs_1 = frozenset((1, 2))
fs_2 = frozenset((2, 1))
This is an extremely handy tool that renders a graphical representation of the objects in memory while the code is executed step by step. I'm attaching a screenshot:
Solution 2:[2]
The answer by Tonechas is wrong.
frozenset is unordered, but it can be used for equality comparison. Quote from the python official doc:
Both set and frozenset support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ashiato |

