Home > database >  Why does this while loop never stops in Python
Why does this while loop never stops in Python

Time:10-09

I am trying to generate a list of 100 unique random numbers using Python 3.8. For this I am using the following block of code:

import random

list_1_unique = [random.randint(0,30)]


for i in range(1, 100):
    x = random.randint(0, 30)
    while x in list_1_unique:
        x = random.randint(0, 30)
    list_1_unique.append(x)
    
list_1_unique

But once I run it Ipython console never stops, so it enters in eternal loop and I do not understand why? Can anybody guess why?

CodePudding user response:

The following condition is causing the infinite loop:

while x in list_1_unique

If x happens to be in the list when hitting the while loop the first time, you are gone. Since this is repeated 100 times, guess what, it's bound to happen.

CodePudding user response:

The number of times you run the for loop is greater than the the number of possible different values you can get from your randint, so after 30 or so step your list list_1_unique will have all possible values and in the 31° step you get into an infinite loop because any value of x you generate will be in your list and thus you can't get out of the while loop.

In other words, you can't pick 100 objects from a box containing only 30.

If you want a sample of N random numbers better use random.sample

>>> import random
>>> random.sample(range(1000),10)
[840, 872, 312, 952, 826, 867, 99, 4, 132, 745]
>>> 
  • Related