How does for loop works here

Screen Link: https://app.dataquest.io/m/1009/lists-and-for-loops-practice-problems/11/understanding-code-5

My Code: for i in range(10):
print(i)
i = 11

why doesn’t the third line (i = 11) have any impact on the output of this code. It still prints 0 -> 9.
Even if I put i = 8 instead of 11, there is no change in output.

1 Like

Hi @srivastava.anurag008

Well python reads line per line, so when it finds a print statement executes it before reading the next line. That’s why that third line doesn’t have an impact in the value of i inside the loop

2 Likes

Answered your query here @srivastava.anurag008.

2 Likes

shouldn’t the value of “i” gets updated due to third line?

@aashish72k: Kindly refer to the explanation I have provided in the link above.

range() is of immutable type as described in this article meaning you cannot change the value in which the iterator goes over by attempting to change the iterator value.

1 Like