I'd like to generate a set of x unique random numbers and sort them in Python. For example: range(1000, 10000) x = 100
I've figured out to import random and use the random.randrange method, then loop to get 100 random numbers and in the end sort them.
However, I don't know how to get unique numbers (such that they do not repeat) - should I validate each and every loop? Or is there any other easier way how to do it? And how should I sort them?
Thanks y'all!
more_itertools
implements therandom_combinations
itertools recipe, which returnsr
sorted random numbers, if given a sorted input.This is unlike
random.sample
, which returns an unsorted result.Details
Looking at the recipe, we can see why this order is established.
From itertools recipes:
range()
is inherently sorted and becomes thepool
from which random elements are selected. Although the indices are randomly selected, they are later sorted. Since thepool
andindices
are both sorted, the results are also sorted.In summary, this does the same as @Volatility's answer, except the sorting is handled for you.
Cavaet:
random_combinations
requires the length of the iterable to exceed the value ofr
, otherwise an error is raised.Use
random.sample
The sorting part is easy - use the
list.sort
method.By default this will sort it from smallest number to largest, but it takes an optional
key
argument which determines what to sort it on.There is also a
sorted
function which doesn't modify a list in-place, but rather returns a sorted list.This also has an optional
key
argument.