Reputation: 1121
So let's say I have a list of numbers (not a specific range, which could change), and want to generate a random number which excludes the numbers in the list.
List of excluded numbers comes from a sql query.
and the only limit for the random number is the number of digits, which can come from:
random_number = ''.join(random.choice(chars) for _ in range(size))
so I want to generate the random number (with size limit) excluding a list of numbers.
while random_number in exclude_list:
random_number = ''.join(random.choice(string.digits) for _ in range(size))
Is there a pythonic way (other than using while loop) to do that?
example: generate a 2digit random number which does not exist in a list of numbers like exclude_list=[22,34,56,78]
Upvotes: 0
Views: 2966
Reputation: 48057
You may call the random.choice
using set
to exclude the items in list you do not want to be the part of random selection:
>>> import random
>>> my_list = [1, 2, 3, 4, 5, 6, 7]
>>> exclude_list = [3, 6, 7]
# list containing elements from `my_list` excluding those of `exclude_list`
>>> valid_list = list(set(my_list) - set(exclude_list))
>>> random.choice(valid_list)
5 # valid random number
Upvotes: 6