Use frozenset as a couple in python

I would like to make a pair of two elements. I am not interested in the order of the elements, so I use frozenset .

I can come up with the following two methods for repeating elements from a freezet. Isn't there any fancy 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] 
+6
python immutability set
source share
3 answers
 pair = frozenset([element1, element2]) elem1, elem2 = pair 
+16
source share

If you have many such pairs, using frozenset() NOT a good idea. Use tuples instead.

 >>> import sys >>> fs1 = frozenset([42, 666]) >>> fs2 = frozenset([666, 42]) >>> fs1 == fs2 True >>> t1 = tuple(sorted([42, 666])) >>> t2 = tuple(sorted([666, 42])) >>> t1 == t2 True >>> sys.getsizeof(fs1) 116 >>> sys.getsizeof(t1) 36 >>> 

Update Bonus: Sorted tuples have a predictable iteration sequence:

 >>> for thing in fs1, fs2, t1, t2: print [x for x in thing] ... [42, 666] [666, 42] [42, 666] [42, 666] >>> 

Update 2 ... and their repr () are the same thing:

 >>> repr(fs1) 'frozenset([42, 666])' >>> repr(fs2) 'frozenset([666, 42])' # possible source of confusion >>> repr(t1) '(42, 666)' >>> repr(t2) '(42, 666)' >>> 
+8
source share

If these are just two elements, you de-sequence them. But I'm not sure what you're trying to do here with frozenset

 >>> s = frozenset([1,2]) >>> s frozenset({1, 2}) >>> x,y = s >>> x 1 >>> y 2 
+1
source share

All Articles