Reputation: 799
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
Upvotes: 0
Views: 183
Reputation: 1934
range(100)
is a list of integers from 1 to 100 over which you are supposed to iterate. So, len(range(100)
= 100. In python 2.x, a list is always greater than an integer. A very simple way to fix this problem is:
i=0
while i < 100: # instead of range(100)
print i
i += 9
Upvotes: 0
Reputation: 142136
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
Upvotes: 8