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): r=random.randint(1,100) if r not in list: list.append(r)
>>> list [68, 87, 18, 41, 54]