0

loop limit question

Hi could someone please help me to understand something in PY? Say I have the code: l = [] for i in range(1,1000): l.append(i) if l[-1] > 98: break print(l) will give me a list starting from 1 (which is what I want) but it stops at 99 and not at 98. I know I can limit in the range statement but I actually want to understand why the loop does not stop at 98 since 99 is in fact >98 (for another problem). Cheers

22nd Feb 2018, 12:38 PM
Marco Polidori
Marco Polidori - avatar
4 Answers
0
why don't you break if i >= 98, then it stops at 98 itself.
22nd Feb 2018, 2:10 PM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar
+ 1
break is executed only if the last element appended is greater than 98. Since 98 is not strictly greater than 98, it continues. once i become 99, it breaks. so at the end of the loop i has the value 99.
22nd Feb 2018, 1:59 PM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar
0
Thanks Ravi. Makes sense, since the if statement is below the iteration. Is there any way I can change the code to get a hard stop during an iteration? Cheers
22nd Feb 2018, 2:07 PM
Marco Polidori
Marco Polidori - avatar
0
How embarrassing. X) I thought I tried it without success but you are right, this does the trick
22nd Feb 2018, 2:12 PM
Marco Polidori
Marco Polidori - avatar