pick randomly a certain fraction of numbers from a list

Raymond Hettinger vze4rx4y at verizon.net
Fri Feb 14 13:42:36 EST 2003


"Yuval"
> 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.

The simple way is to do a random.shuffle() of the list and
then slice-off the first x% elements.

A complete, efficient algorithm for random sampling without
replacement is in the list of recipes at ActiveState's python
cookbook site.


Raymond Hettinger






More information about the Python-list mailing list