coolstoner coolstoner - 3 months ago 12
Python Question

infinite while loop in python when integer compared with range

my while code:

i=0
a = range(100)
while i < range(100):
print i
i += 9


this goes into an infinite loop...may i know why?

is it because an integer is compared to the list?
but what happens when i becomes greater than 99?

shouldnt it come out of the while loop?

below code works fine as expected:

i=0
a = range(100)
a_len = len(a)
while i < a_len:
print i
i += 9

Answer

Sadly in Python 2.x, an int is always less than a list (even if that list is empty).

>>> 9 < []
True

What you want to be doing is using the 3-argument form of range so you have a start, a stop and a step, eg:

for i in range(0, 100, 9):
    print i