I would like to make a pair of two elements. I don't care about the order of the elements, so I use frozenset
.
I can think of the following two methods to iterate the elements back from the frozenset. Isn't there any fancier method? Thanks in advance.
pair = frozenset([element1, element2])
pair2 = list(pair)
elem1 = pair2[0]
elem2 = pair2[1]
pair = frozenset([element1, element2])
elems = []
for elem in pair:
elems.append(elem)
elem1 = elems[0]
elem2 = elems[1]
Just to elaborate on an above comment, and assuming your elements are easily sortable, you could make an unordered pair class from
tuple
using:Then you get:
If it is just two elements you are de-sequence them. But I am not sure, what you are trying to do here with the frozenset
If you have a lot of those pair things, using
frozenset()
is NOT a good idea. Use tuples instead.Update Bonus: sorted tuples have a predictable iteration sequence:
Update 2 ... and their repr() is the same: