There is a list of fixed numbers y = [1,45,66,22,1988] , and there is also a variable x = random.randrange (1,1999)

I try to run the variable x in the While loop until x equals one of the numbers in the list y

y = [1,45,66,22,1988] x = 0 while ( x not in y ): print("X = ",x) x = random.randrange(0,1999) 

The problem is that the cycle can stop if even x is not equal to one of the numbers in the list y . The final result was the number 305 .

How can this be fixed?

  • Theoretically, it is possible that your cycle will never stop, because never drop a number from the list. The event is unlikely, even very-very unlikely, but why risk it? It is much easier to take a number not from rank by value, but from rank by number: x = random.randrange(0, len(y)) , then the resulting x is the key of the required element ( y[x] ). And the element from the list will always be found in one iteration, and not over a random period of time. - BOPOH

2 answers 2

You do not print the last X value that falls into the y list:

 y = [1,45,66,22,1988] x = 0 while ( x not in y ): print("X = ",x) x = random.randrange(0,1999) print("X in y, X=", x) 

    I risk answering a little off topic, but it may be useful. What do you want to achieve with your code? Choose arbitrary from list y ? Then it is better to do it like this:

     from random import choice y = [1,45,66,22,1988] x = choice(y)