Reading a random element from a set
Peter Otten
__peter__ at web.de
Wed Jul 26 03:54:56 EDT 2017
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)
>
> any better idea, in a single instruction ?
>>> next(itertools.islice(a, random.randrange(len(a)), None))
0
While this gives you a random element I agree that it's not nice in every
other aspect.
More information about the Python-list
mailing list