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?
Advertisement
Answer
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,
set
andfrozenset
. Theset
type 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. Thefrozenset
type 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: