Reading a random element from a set

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jul 26 03:16:59 EDT 2017


On Wed, 26 Jul 2017 08:58:03 +0200, ast wrote:

> Hello
> 
> random.choice on a set doesn't work because sets are not indexable
> 
> so I found nothing better than taking an element and puting it back
> 
> a = {5, 7, 8, 3, 0, 8, 1, 15, 16, 34, 765443}
> elt = a.pop()
> a.add(elt)


That's not *random*, it is arbitrary but predictable. If you try it twice 
in a row, you will probably get the same element each time. (Depends on 
the elements, but very likely.)


>>> a = {5, 7, 8, 3, 0, 8, 1, 15, 16, 34, 765443}
>>> elt = a.pop()
>>> a.add(elt)
>>> elt
0
>>> a.pop()  # likely to be zero again
0


> any better idea, in a single instruction ?


If you know the set is not empty, you can do:

element = next(iter(a))


but that has the same problem as above: the choice won't be random, and 
each time you do it you'll get the same element:


>>> next(iter(a))  # after popping zero and not adding it again
1
>>> next(iter(a))
1


If you need a random element, best way is:



>>> random.choice(list(a))
8
>>> random.choice(list(a))
15
>>> random.choice(list(a))
16



-- 
“You are deluded if you think software engineers who can't write 
operating systems or applications without security holes, can write 
virtualization layers without security holes.” —Theo de Raadt



More information about the Python-list mailing list