pick randomly a certain fraction of numbers from a list

Peter Hansen peter at engcorp.com
Fri Feb 14 19:40:18 CET 2003

Yuval wrote:
> Does anybody know a quick way of picking randomly x% of elements from a list.
> e.g. If I have a list of 50 elements, how do I randomly choose 2% of it?
> The trivial way would be to iterate with the random.choice() function.
> Is there any better way?

>>> import random
>>> a = range(50)
>>> random.shuffle(a)
>>> a[:int(.02*len(a))]

Other than deciding how you want to account for rounding errors etc,
this should do it.


More information about the Python-list mailing list