To generate random numbers without repeating in Python, you can use the random module function choices(). choices() takes a list and the number of random numbers you want to generate.
import random
lst = range(0,100)
print(random.choices(lst, k=10))
#Output:
[37, 95, 88, 82, 15, 38, 60, 71, 56, 49]
When working with data, it can be very useful to generate random numbers to be able to perform simulations or get a random sample of a dataset.
In Python, we can generate random numbers in a range easily. The Python random module has many useful functions for generating random numbers.
The generation of random numbers is pretty easy, but sometimes we need to generate random numbers and have all of our numbers be unique.
In Python, you can easily generate random numbers without repeating.
To generate random numbers without repeating in Python, you can use the random module function choices(). choices() takes a list and the number of random numbers you want to generate.
Below is a simple example of how to generate random numbers between 0 and 100 without repeating in Python.
import random
lst = range(0,100)
print(random.choices(lst, k=10))
#Output:
[37, 95, 88, 82, 15, 38, 60, 71, 56, 49]
Generating Random Numbers from a List of Numbers Without Repeating in Python
If you have a list of numbers that you want to get random numbers from without repeating, there is an extra step you need to take.
First, if you have a list of numbers, we need to remove duplicates so that we can use choices().
To remove the duplicates from your list, you should convert it to a set with set(). Then, you can convert it back to a list and use choices().
Below is an example of how to generate non-repeating random numbers with Python from a list of numbers with duplicates.
import random
lst = [0,0,1,2,2,3,4,5,5,5,6,7,8,9,9,9,10]
lst_without_dups = list(set(lst))
print(random.choices(lst_without_dups, k=5))
#Output:
[9, 0, 8, 3, 6]
Hopefully this article has been useful for you to learn how to generate a list of random numbers without repeating in Python.