0

I'm using range() function to execute a for loop in python like

for i in range(5):
    print(i)
print(i)

I'm wondering why the final print prints i with value of 4 instead of 5? I thought the final execution of the final loop will increase i to the value of 5 which breaks the conditional? Thanks!

  • 1
    The implied start value for the range is zero. *range()* will generate 5 sequential numbers - i.e., 0,1,2,3,4 – DarkKnight Oct 02 '22 at 07:44
  • 1
    Which conditional do you mean? – mkrieger1 Oct 02 '22 at 07:44
  • Because it's not a while loop under the hood. There's a list or an iterator behind the scene. – yansainity Oct 02 '22 at 07:45
  • @deceze I can tell Chason though there must be a while loop. Something like: for(int i =0;i<5;i++) – yansainity Oct 02 '22 at 07:52
  • I mean if we write a for loop like in cpp as @eason_yan pointed out as `int i = 0; for (; i<5; i++){} cout<< i;`, when the loop ends if we print the value of i, it should be 5 while in python if we use `range` it will be 4 – Chason Young Oct 02 '22 at 18:33

0 Answers0