Random integer with random.randint without certain number
Question:
I am trying to generate a random number.
import random
print(random.randint(1,10))
Would I be able to generate a number between 1-10 but without ever generating x?
For example x = 3
Answers:
Three approaches:
-
Loop until it’s valid:
while (val := random.randint(1, 10)) == 3: # Python 3.8+, pre-3.8 is more verbose
pass
print(val)
-
Generate from a smaller range, then increment all numbers equal to or higher than the excluded value:
val = random.randint(1, 9)
if val >= 3:
val += 1
print(val)
-
Create a sequence of the numbers you allow, and use random.choice
(probably the best solution if you’re doing this many times; make the sequence once, then reuse it after):
# Done once (must convert back to sequence from set, choice only works with sequences)
values = tuple(set(range(1, 11)) - {3})
# Done as often as you like
print(random.choice(values))
If you use choice you can provide a list of acceptable values:
random.choice([[1,2,4,5,6,7,8,9]])
Onliner, using range
and sets
:
x = 3
print(random.choice(list(set(range(1,11))-{x})))
# list(set(range(1,11))-{x})) -> [1, 2, 4, 5, 6, 7, 8, 9, 10]
I am trying to generate a random number.
import random
print(random.randint(1,10))
Would I be able to generate a number between 1-10 but without ever generating x?
For example x = 3
Three approaches:
-
Loop until it’s valid:
while (val := random.randint(1, 10)) == 3: # Python 3.8+, pre-3.8 is more verbose pass print(val)
-
Generate from a smaller range, then increment all numbers equal to or higher than the excluded value:
val = random.randint(1, 9) if val >= 3: val += 1 print(val)
-
Create a sequence of the numbers you allow, and use
random.choice
(probably the best solution if you’re doing this many times; make the sequence once, then reuse it after):# Done once (must convert back to sequence from set, choice only works with sequences) values = tuple(set(range(1, 11)) - {3}) # Done as often as you like print(random.choice(values))
If you use choice you can provide a list of acceptable values:
random.choice([[1,2,4,5,6,7,8,9]])
Onliner, using range
and sets
:
x = 3
print(random.choice(list(set(range(1,11))-{x})))
# list(set(range(1,11))-{x})) -> [1, 2, 4, 5, 6, 7, 8, 9, 10]