0

If I had a list that ranged from 0 - 9 for example. How would I use the random.seed function to get a random selection from that range of numbers? Also how I define the length of the results.

import random

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a = 10
random.seed(a)
length = 4

# somehow generate random l using the random.seed() and the length.
random_l = [2, 6, 1, 8]
2
  • You wouldn't; that isn't what random.seed() does. Are you more interested in what random.seed() actually does, or are you more interested in producing the random list? Commented Mar 7, 2013 at 20:59
  • Are duplicates allowed? Commented Mar 7, 2013 at 20:59

3 Answers 3

13

Use random.sample. It works on any sequence:

>>> random.sample([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
[4, 2, 9, 0]
>>> random.sample('even strings work', 4)
['n', 't', ' ', 'r']

As with all functions within the random module, you can define the seed just as you normally would:

>>> import random
>>> lst = list(range(10))
>>> random.seed('just some random seed') # set the seed
>>> random.sample(lst, 4)
[6, 7, 2, 1]
>>> random.sample(lst, 4)
[6, 3, 1, 0]
>>> random.seed('just some random seed') # use the same seed again
>>> random.sample(lst, 4)
[6, 7, 2, 1]
>>> random.sample(lst, 4)
[6, 3, 1, 0]
Sign up to request clarification or add additional context in comments.

1 Comment

How would I define the seed with sample()?
1

If you got numpy loaded, you can use np.random.permutation. If you give it a single integer as argument it returns a shuffled array with the elements from np.arange(x), if you give it a list like object the elements are shuffled, in case of numpy arrays, the arrays are copied.

>>> import numpy as np
>>> np.random.permutation(10)
array([6, 8, 1, 2, 7, 5, 3, 9, 0, 4])
>>> i = list(range(10))
>>> np.random.permutation(i)
array([0, 7, 3, 8, 6, 5, 2, 4, 1, 9])

Comments

0
import random

list = [] # your list of numbers that range from 0 -9

# this seed will always give you the same pattern of random numbers.
random.seed(12) # I randomly picked a seed here; 

# repeat this as many times you need to pick from your list
index = random.randint(0,len(list))
random_value_from_list = list[index]

3 Comments

If you don't care about seed. poke's random.sample() is the way to go
Note that you can still define the seed when using sample. All the functions in the random module respect the seed.
How would I define the seed with sample()?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.