I would like to get an element from a frozenset
(without modifying it, of course, as frozenset
s 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?
The Python frozenset() method returns a new frozenset object whose elements are taken from the passed iterable . If iterable is not specified, a new empty set is returned. Note: The elements must be hashable. When nothing is specified, the frozenset() method returns an empty frozenset object to fz .
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.
Python frozenset() Function The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable).
(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']
If you know that there is but one element in the frozenset, you can use iterable unpacking:
s = frozenset(['a'])
x, = s
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..:
>>> timeit.timeit('a,b = foo', setup='foo = frozenset(range(2))', number=100000000)
5.054765939712524
>>> timeit.timeit('a = next(iter(foo))', setup='foo = frozenset(range(2))', number=100000000)
11.258678197860718
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With