Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *