I'd like to create a random list of numbers in python, but exclude a certain number, k.
I can create a random list of integers:
l = [random.randint(0,10) for i in range(5)]
Then I can remove the number, k, if it's there, and add another random number in the range, but this seems like too many steps.
In researching this, It's quite easy to find out how to create a random number from a range and exclude a certain number, for example:
print (choice([i for i in range(0,9) if i not in [2,5,7]]))
I could do this the amount of times I need to create the array -- but this seems more complex than necessary.
Would appreciate some feedback this
Make a list of the numbers in the range, and remove k
from the list. Then you can use random.choices()
to select multiple elements from the list.
numbers = list(range(0, 11))
numbers.remove(k)
result = random.choices(numbers, k=5)
You could write a generator that yields random numbers of your choosing, and take the first n:
def random_numbers_except(a, b, exclusions):
while True:
while (choice := random.randint(a, b)) in exclusions:
pass
yield choice
numbers = [number for _, number in zip(range(5), random_numbers_except(0, 10, [2, 5, 7]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With