Generate random numbers except a particular number in a Python list

Hello everyone, in this tutorial, we will learn to generate random numbers except a particular number in a Python list. We are going to use random.choice() method with the list comprehension technique to get the desired result. See how we can do it.

First, let us try to understand the working of random.choice() method. This method returns a random number from a Python list or tuple.

Now, to get a random number from the given list except a given value we first use the list comprehension method to get the list of elements that are not equal to the given particular value which needs to be avoided while generating the random number from the list. Then we can use the choice() method explained above to get any random value from this newly created list.

To learn about list comprehension, visit this post: List and dictionary comprehension in python

Okay, so now we are going to implement the above-explained algorithm through Python code. Have a thorough look at the given example program to clear any doubt.

Let’s say there is a list with its elements as 1, 3, 5, 6, 8 and 9. Now we need to get a number from this list randomly except 8. To do this, we need to write our Python program as shown below.

import random

given_list = [1, 3, 5, 6, 8, 9]

#we want random number except 8
n = 8

new_list = [el for el in given_list if el != n]
random_number = random.choice(new_list)

print("Random number generated is ", random_number)

Output:

Random number generated is 5

I hope this post was helpful. Thank you.

Also read: Python | Select a random item from a list in Python

Leave a Reply

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