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'])
iter(s).next()
which returns, as expected:
'a'
In other words, is there any way of 'popping' an element from a frozenset without actually popping it?
If you know that there is but one element in the frozenset, you can use iterable unpacking:
This is somewhat a special case of the original question, but it comes in handy some times.
If you have a lot of these to do it might be faster than next(iter..:
(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 thaniter(s).next()
.If you want a random element rather than an arbitrary one, use the following:
Here are a couple of examples demonstrating the difference between those two:
You could use with python 3: