Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'])
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?

like image 600
ablondin Avatar asked Jul 23 '13 04:07

ablondin


People also ask

How do you access the elements of a Frozenset in Python?

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 .

How do you 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.

What does a Frozenset do in Python?

Python frozenset() Function The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable).


2 Answers

(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']
like image 166
Zero Piraeus Avatar answered Sep 22 '22 07:09

Zero Piraeus


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
like image 38
Dominic Kempf Avatar answered Sep 24 '22 07:09

Dominic Kempf