31

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]
nbro
  • 15,395
  • 32
  • 113
  • 196
user63503
  • 6,243
  • 14
  • 41
  • 44

4 Answers4

63

A random sample like this returns list of unique items of sequence. Don't confuse this with random integers in the range.

>>> import random
>>> random.sample(range(30), 4)
[3, 1, 21, 19]
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • 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. – user63503 Aug 24 '10 at 18:00
16

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

import random
[random.randrange(1, 10) for _ in range(0, 4)]
Manoj Govindan
  • 72,339
  • 21
  • 134
  • 141
1
import random


def simplest(list_length):
    core_items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    random.shuffle(core_items)
    return core_items[0:list_length]

def full_random(list_length):
    core_items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    result = []
    for i in range(list_length):
        result.append(random.choice(core_items))
    return result
ChantOfSpirit
  • 157
  • 1
  • 1
  • 9
0

You can achieve this using random.choices() if you want to sample with replacement.

>>> import random
>>> random.choices(range(15), k=3)
[24, 29, 17]