How to create a list of random numbers without duplicates with Python?

Sometimes, we want to create a list of random numbers without duplicates with Python.

In this article, we’ll look at how to create a list of random numbers without duplicates with Python.

How to create a list of random numbers without duplicates with Python?

To create a list of random numbers without duplicates with Python, we can use the random.sample method.

For instance, we write:

import random

l = random.sample(range(100), 10)
print(l)

We call random.sample with the range of numbers to generate and the number of random numbers to generate respectively.

We generate numbers between 0 and 99 with range(100).

And then we assign the returned list to l.

Therefore, l is something like [34, 77, 97, 83, 22, 28, 74, 93, 59, 87].

Conclusion

To create a list of random numbers without duplicates with Python, we can use the random.sample method.