+3 votes
in Programming Languages by (15.7k points)

I am selecting some elements from a list using random.sample() function. But it gives me different sets of elements every time. How can I get the same set of elements every time?

E.g. In the following example, I am getting different sets of elements.

>>> import random

>>> a=[i for i in range(20)]

>>> a

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> random.sample(a,5)

[17, 3, 6, 1, 14]

>>> random.sample(a,5)

[18, 6, 2, 11, 8]

>>> random.sample(a,5)

[14, 4, 15, 18, 0]

1 Answer

0 votes
by (27.1k points)

You can use the seed() function to set a random seed before using the sample() function.

Here is an example:

>>> import random
>>> a=[i for i in range(20)]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> random.seed(1)
>>> random.sample(a,5)
[4, 18, 2, 8, 3]
>>> random.seed(1)
>>> random.sample(a,5)
[4, 18, 2, 8, 3]

Related questions

...