How to exclude certain numbers with random.randint?

Will there be any possibility to exclude for example: the number 50, 99, 80 for so that it is not printed?

x = (random.randint(1, 100))
print(x)

4voto

I copy exactly what it says in this question:

from random import choice

print(choice([i for i in range(0,9) if i not in [2,5,7]]))

In your case print(choice([i for i in range(1,101) if i not in [50,99,80]]))

As César adds in the comments, the range that returns random.randint is inclusive, so for it to include 100, you should put 101.

In fact, in his case it would be range(1, 101) because the range used by random.randint is inclusive.

Right @César, I modify it, thank you very much.

3voto

Patricio Moracho Points 24098

A similar but somewhat different approach to Adrian's answer, provided the list of cases is relatively small, is:

• generate a list of all possible values to choose from
• generate a random value but to use as a list selection index.

import random
elementos = [n for n in range(0, 101) if n not in [50, 99, 80]]
x = elementos[random.randint(0, len(elementos))]

It may eventually be more optimal if the number of excluded values is significant.

The last part should start from 0, it would be elementos[random.randint(0, len(elementos) - 1)] but you are excluding the first element, and at the end restartle one so that it does not give a IndexError . Remember that these are positions in a list.

@César, that's totally true, I was in R mode (where the positions start from 1). 