Fix Python – Select 50 items from list at random

Question

Asked By – O.rka

I have a function which reads a list of items from a file. How can I select only 50 items from the list randomly to write to another file?

def randomizer(input, output='random.txt'):
    query = open(input).read().split()
    out_file = open(output, 'w')
    
    random.shuffle(query)
    
    for item in query:
        out_file.write(item + '\n')   

For example, if the total randomization file was

random_total = ['9', '2', '3', '1', '5', '6', '8', '7', '0', '4']

and I would want a random set of 3, the result could be

random = ['9', '2', '3']

How can I select 50 from the list that I randomized?

Even better, how could I select 50 at random from the original list?

Now we will see solution for issue: Select 50 items from list at random


Answer

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

Otherwise, use

import random
random.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)

This question is answered By – John La Rooy

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0