views:

78

answers:

2

How to generate a random (but unique and sorted) list of a fixed given length out of numbers of a given range in python?

Something like that:

>>>> list_length = 4
>>>> values_range = [1,30]
>>>> random_list(list_length,values_range)

[1,6,17,29]

>>>> random_list(list_length,values_range)

[5,6,22,24]

>>>> random_list(3,[0,11])

[0,7,10]
+1  A: 

A combination of random.randrange and list comprehension would work.

import random
[random.randrange(1, 10) for count in range(0, 4)]
Manoj Govindan
+3  A: 
>>> import random
>>> random.sample(range(30), 4)
[3, 1, 21, 19]
SilentGhost
`random.sample` returns list of *unique* items of sequence.
phadej
Thank you!I'd add assigning result to a variable and doing variable.sort() on it to match example above, but I did not ask for it explicitly, so, your solution is the best.