How to get an arbitrary element from frozenset?

I would like to get an element from frozenset (of course, without changing it, since frozenset are immutable). The best solution I have found so far:

 s = frozenset(['a']) iter(s).next() 

which returns as expected:

 'a' 

In other words, is there a way to β€œpush” an element out of a frozenset without actually pushing it?

+12
source share
3 answers

(Summing up the answers given in the comments)

Your method is as good as any, with the caveat that from Python 2.6 you should use next(iter(s)) , not iter(s).next() .

If you need a random element, not an arbitrary one, use the following:

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

Here are some examples that demonstrate the difference between the 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'] 
+10
source

If you know that there is only one element in frozenset, you can use iterative unpacking:

 s = frozenset(['a']) x, = s 

This is a somewhat special case of the original question, but it will come in handy several times.

If you have a lot of them, it can be faster than the 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 
+10
source

You can use with python 3:

 >>> s = frozenset(['a', 'b', 'c', 'd']) >>> x, *_ = s >>> x 'a' >>> _, x, *_ = s >>> x 'b' >>> *_, x, _ = s >>> x 'c' >>> *_, x = s >>> x 'd' 
+3
source

Source: https://habr.com/ru/post/950039/


All Articles