George Francis
George Francis

Reputation: 502

How to obtain the same random sample from a list in Python

I have a small script to get a random sample from a list, however I want to always get the same list whenever I run this script. How should I do this?

My code currently is as follows, however each time that I run the script, I get a different sample.

import random

def SampleWithoutRepetition(population, sampleSize):
    random.seed(100)
    result =  random.sample(set(
        map(lambda attribute: attribute, population)), sampleSize)
    print(f"result: {result}")

population = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']

SampleWithoutRepetition(population, 4)

Upvotes: 2

Views: 3892

Answers (1)

TerhorstD
TerhorstD

Reputation: 295

the set() is an unordered container which does not preserve the order of your population. Like this you choose exactly the same sample from different populations each time the set is re-instantiated. Use list() instead, or directly use

result =  random.sample([x for x in population], sampleSize)

In the [] expansion you can calculate the attribute as you probably intended with the lambda. So your script could look like this:

import random
random.seed(100)

def SampleWithoutRepetition(population, sampleSize):
    func = lambda attribute: attribute
    return random.sample([func(x) for x in population], sampleSize)

population = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']

print(SampleWithoutRepetition(population, 4))

If you keep the random.seed in the function, it will return the same sample each time you call the function, if you put it outside, you receive the same sample each time you call the script, as requested in your question.

Upvotes: 9

Related Questions