Select 50 items from list at random to write to file Select 50 items from list at random to write to file python python

Select 50 items from list at random to write to file


If the list is in random order, you can just take the first 50.

Otherwise, use

import randomrandom.sample(the_list, 50)

random.sample help text:

sample(self, population, k) method of random.Random instance    Chooses k unique random elements from a population sequence.    Returns a new list containing elements from the population while    leaving the original population unchanged.  The resulting list is    in selection order so that all sub-slices will also be valid random    samples.  This allows raffle winners (the sample) to be partitioned    into grand prize and second place winners (the subslices).    Members of the population need not be hashable or unique.  If the    population contains repeats, then each occurrence is a possible    selection in the sample.    To choose a sample in a range of integers, use xrange as an argument.    This is especially fast and space efficient for sampling from a    large population:   sample(xrange(10000000), 60)


One easy way to select random items is to shuffle then slice.

import randoma = [1,2,3,4,5,6,7,8,9]random.shuffle(a)print a[:4] # prints 4 random variables


I think random.choice() is a better option.

import numpy as npmylist = [13,23,14,52,6,23]np.random.choice(mylist, 3, replace=False)

the function returns an array of 3 randomly chosen values from the list