Random choice of random module in Python with no repeat

In this tutorial, we will learn how to generate random numbers in Python from a given list or between a range of elements. We will use the random.choice() from the random module of Python.

Using Python random.choice()

In Python, Random is a module, that has an inbuilt choice() function that chooses a random element from a given list. Let us see how we can implement this random module in Python. For that, let us declare a list of objects.

# Declare a list
A = [23,44,65,78,99,11,67,33,88]

Moving forward, we will import the random module and use the random.choice() syntax to generate a random variable from the above declared list.

import random

# Generating a random element
X = random.choice(A)
print("Random element generated is",X)


Random element generated is 78

Here, we have seen how to generate an element from a declared list. But what if we want to generate an entire list with random values? Let us see how to do that.

import random
list = []
for i in range(5):
          if r not in list: list.append(r)


>>> list
[68, 87, 18, 41, 54]
In this example we have generated a list of 5 elements within the range of 1 to 100 using the random.radint() syntax. Also, since we do not want  any repetition in the values, we check every element if it appears in list or not. If no repetition has occurred, the generated element gets appended at the end of the list.


Leave a Reply

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