ablondin ablondin - 27 days ago 17
Python Question

How to get an arbitrary element from a frozenset?

I would like to get an element from a frozenset (without modifying it, of course, as frozensets are immutable). The best solution I have found so far is:

s = frozenset(['a'])

which returns, as expected:


In other words, is there any way of 'popping' an element from a frozenset without actually popping it?


(Summarizing the answers given in the comments)

Your method is as good as any, with the caveat that, from Python 2.6, you should be using next(iter(s)) rather than iter(s).next().

If you want a random element rather than an arbitrary one, use the following:

import random
random.sample(s, 1)[0]

Here are a couple of examples demonstrating the difference between those two:

>>> s = frozenset("kapow")
>>> [next(iter(s)) for _ in range(10)]
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
>>> import random
>>> [random.sample(s, 1)[0] for _ in range(10)]
['w', 'a', 'o', 'o', 'w', 'o', 'k', 'k', 'p', 'k']