191

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?

0

5 Answers 5

387

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)
2
  • 1
    Can I have random.sample return also the indices it has chosen?
    – zyy
    Mar 30, 2020 at 0:54
  • 1
    Make it sample from a list of indices (range(len(list)) then reconstruct the sample from the list of random indices and the original list.
    – Jedai
    Dec 11, 2020 at 7:26
52

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

import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables
2
  • @MonicaHeddneck Why would random shuffling and slicing be better? Wouldn't selecting a number of sample by randomizing the selection have the same merits as random shuffling and then taking a slice of the shuffled samples? Can you please explain? Thanks.
    – salvu
    Jul 28, 2017 at 14:39
  • 7
    I used this to easily create a test / train set for a machine learning project. Using random.choice(mylist,3) wouldn't create two disjoint sets as this did. Jul 31, 2017 at 23:38
45

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

import numpy as np

mylist = [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

3
  • 7
    I think you need to use random.choice(mylist, 3, replace=False). Also less confusing to use import numpy as np and np.random.choice(mylist, 3, replace=False) Oct 24, 2016 at 23:38
  • 11
    This is has chances of repeating the list item
    – Paullo
    Feb 10, 2018 at 20:18
  • 1
    No this is not a better option, it is ~100 times slower Jan 13, 2020 at 6:51
2
  1. we have 3 samples ('orange','mango','apple'). Created series, should contain 7 elements & randomly selected from list.

    random.choice
    import random
    
    import numpy as np
    
    fruits = ['orange','mango','apple']
    
    np.random.choice(fruits, 7, replace=True)
    

    Output

    array(['orange', 'mango', 'apple', 'orange', 'orange', 'mango', 'apple'],
          dtype='<U6')
    
  2. Random selection from list (less than 3 values)

    random.sample
    import random
    
    random.sample(fruits, 3)
    
-4

Say your list has 100 elements and you want to pick 50 of them in a random way. Here are the steps to follow:

  1. Import the libraries
  2. Create the seed for random number generator, I have put it at 2
  3. Prepare a list of numbers from which to pick up in a random way
  4. Make the random choices from the numbers list

Code:

from random import seed
from random import choice

seed(2)
numbers = [i for i in range(100)]

print(numbers)

for _ in range(50):
    selection = choice(numbers)
    print(selection)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.