{"id":12768,"date":"2021-09-30T16:30:38","date_gmt":"2021-09-30T11:00:38","guid":{"rendered":"https:\/\/python-programs.com\/?p=12768"},"modified":"2021-11-22T18:33:34","modified_gmt":"2021-11-22T13:03:34","slug":"python-program-to-generate-random-numbers-except-for-a-particular-number-in-a-list","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-program-to-generate-random-numbers-except-for-a-particular-number-in-a-list\/","title":{"rendered":"Python Program to Generate Random Numbers except for a Particular Number in a List"},"content":{"rendered":"

In this article, we will learn how to create random numbers in Python except for a specific number. To achieve the required result, we will combine the random.choice() function with the list comprehension technique. See what we can come up with.
\nFirst, let’s look at how the random.choice()<\/strong> method works. This method selects a random number from a Python list or tuple and returns it.
\nTo generate a random number from a given list that is not equal to a certain value, we first use the list comprehension method to get a list of elements that are not identical to the provided particular value that must be avoided while generating the random number from the list.<\/p>\n

Then, as previously described, we can use the choice() method to retrieve any random value from the newly generated list.<\/p>\n

Given a list, the task is to generate random numbers except for a particular number in a list in Python.<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given list = [12, 42, 48, 19, 24, 29, 23, 11, 19, 5, 7, 31, 39, 45, 47, 49]\r\nGiven element =19<\/pre>\n

Output:<\/strong><\/p>\n

The Random Element in the given list [12, 42, 48, 19, 24, 29, 23, 11, 19, 5, 7, 31, 39, 45, 47, 49] is [ 7 ]<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given list = [1, 8, 19, 11, 647, 19, 98, 64, 57, 811, 83] \r\nGiven element=8<\/pre>\n

Output:<\/strong><\/p>\n

The Random Element in the given list [1, 8, 19, 11, 647, 19, 98, 64, 57, 811, 83] is [ 19 ]<\/pre>\n

Python Program to Generate Random Numbers except for a particular number in a list<\/h2>\n

Below are the ways to generate random numbers except for a particular number in a list in Python.<\/p>\n