The Python Oracle

How do I create a list of random numbers without duplicates

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 Question
00:48 Accepted answer (Score 285)
01:05 Answer 2 (Score 26)
01:31 Answer 3 (Score 11)
01:53 Answer 4 (Score 10)
04:23 Thank you

--

Full question
https://stackoverflow.com/questions/9755...

Answer 1 links:
[random]: https://docs.python.org/3/library/random...

Answer 2 links:
[Fisher-Yates]: http://en.wikipedia.org/wiki/Fisher%E2%8...
[random.shuffle]: https://docs.python.org/3.6/library/rand...

Answer 3 links:
[Linear Congruential Generator]: https://en.wikipedia.org/wiki/Linear_con...
[has been optimized]: https://docs.python.org/3.7/library/rand...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #random

#avk47



ACCEPTED ANSWER

Score 309


This will return a list of 10 numbers selected from the range 0 to 99, without duplicates.

import random
random.sample(range(100), 10)



ANSWER 2

Score 33


You can use the shuffle function from the random module like this:

import random

nums = list(range(1, 100)) # list of integers from 1 to 99
                           # adjust this boundaries to fit your needs
random.shuffle(nums)
print(nums) # <- List of unique random numbers

Note here that the shuffle method doesn't return any list as one may expect, it only shuffle the list passed by reference.




ANSWER 3

Score 12


You can first create a list of numbers from a to b, where a and b are respectively the smallest and greatest numbers in your list, then shuffle it with Fisher-Yates algorithm or using the Python's random.shuffle method.




ANSWER 4

Score 9


The solution presented in this answer works, but it could become problematic with memory if the sample size is small, but the population is huge (e.g. random.sample(insanelyLargeNumber, 10)).

To fix that, I would go with this:

answer = set()
sampleSize = 10
answerSize = 0

while answerSize < sampleSize:
    r = random.randint(0,100)
    if r not in answer:
        answerSize += 1
        answer.add(r)

# answer now contains 10 unique, random integers from 0.. 100