Let's split down the loops to help you better understand why this is happening.
First, it is important to understand range(...)
. In python range(5)
or list(range(5))
returns [0, 1, 2, 3, 4] which is a list
. range(...)
always returns a list so when you use for loops in python, you are not actually incrementing the actual values, rather you are looping on the list of values generated using range(...), and even if you modify the values, the change would be temporary because as soon as the iteration ends, the looping variable would be assigned the next value in the list generated using range(...)
This is not the case with c++. In c++ for loops works differently where it loops as long as the loop variable (i) < 10 (in your case). No list or array is generated, you are working with integer values, any change you apply to i
doesn't go away because at the end of iteration i
would become i=i+1
.
This is the equivalent of your python code:
for i in [0, 1, 2, 3, 4]:
if (i==2):
i =i -1 # temporary assignment to i-1=2-1 = 1
# temporary because after the loop ends i would become the next value in the list i.e 3
print(i)