Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use frozenset as a pair in python

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]
like image 747
Sangmin Avatar asked Mar 04 '11 05:03

Sangmin


People also ask

What is the use of Frozenset in Python?

Python frozenset() Method creates an immutable Set object from an iterable. It is a built-in Python function. As it is a set object therefore we cannot have duplicate values in the frozenset.

How do you convert a Frozenset to a list?

3) Convert a frozenset to a list. Python frozenset object is an immutable unordered collection of data elements. Therefore, you cannot modify the elements of the frozenset. To convert this set into a list, you have to use the list function and pass the set as a parameter to get the list object as an output.

Why is a Frozenset () different from a regular set?

Python frozenset() It is immutable and it is hashable. It is also called an immutable set. Since the elements are fixed, unlike sets you can't add or remove elements from the set. Frozensets are hashable, you can use the elements as a dictionary key or as an element from another set.


2 Answers

pair = frozenset([element1, element2])
elem1, elem2 = pair
like image 177
kindall Avatar answered Sep 28 '22 19:09

kindall


If you have a lot of those pair things, using frozenset() is 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() is the same:

>>> repr(fs1)
'frozenset([42, 666])'
>>> repr(fs2)
'frozenset([666, 42])' # possible source of confusion
>>> repr(t1)
'(42, 666)'
>>> repr(t2)
'(42, 666)'
>>>
like image 44
John Machin Avatar answered Sep 28 '22 20:09

John Machin