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

Asked By: TNTDoctor

||

Answers:

Three approaches:

  1. Loop until it’s valid:

    while (val := random.randint(1, 10)) == 3:  # Python 3.8+, pre-3.8 is more verbose
        pass
    print(val)
    
  2. 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)
    
  3. 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))
    
Answered By: ShadowRanger

If you use choice you can provide a list of acceptable values:

random.choice([[1,2,4,5,6,7,8,9]])

Answered By: Flow

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]
Answered By: Maurice Meyer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.