Generate random numbers without repetition in Python

In this tutorial, we will learn how to get non-repeating random numbers in Python. There is no in-built function to perform this task. But, we can use some techniques to do this. We will discuss these methods in this tutorial.

Methods we use in this tutorial:

  • random.sample()
  • ramdom.choices()

These two methods take a list as input and select k(input) random elements and return them back. To get non-repeating elements we give a list as input where there are no repeating elements. Even if we already have a list with repeating elements we can convert it to set and back to list this will remove repeating elements. If we don’t have a list and get elements between two numbers we can do that using the range() function.

Let’s look into examples:

Using random.sample() example 1:

random.sample() is an in-built function of Python that gives us a list of random elements from the input list.

#importing required libraries
import random
li=[10,20,30,40,20,30,60,50,60]
#converting list to set so that to remove repeating elements
se=set(li)
li=list(se)
#we use this list to get non-repeating elemets
print(random.sample(li,3))
[60, 50, 20]

Example 2:

Using range() function. This function gives a list of non-repeating elements between a range of elements.

 

#importing required libraries
import random
li=range(0,100)
#we use this list to get non-repeating elemets
print(random.sample(li,3))
[35, 81, 47]

Using random.choices() example 3:

random.choices() is an in-built function in Python. This method takes 2 arguments a list and an integer. This returns a list of a given length that is selected randomly from the given list.

#importing required libraries
import random
li=[10,20,30,40,20,30,60,50,60]
#converting list to set so that to remove repeating elements
se=set(li)
li=list(se)
#we use this list to get non-repeating elemets
print(random.choices(li,k=3))
[50, 10, 60]

Example 4:

#importing required libraries
import random
li=range(0,100)
#we use this list to get non-repeating elemets
print(random.choices(li,k=3))
[21, 81, 49]

Also read:

 

Leave a Reply

Your email address will not be published.