- 1

Python for loop with range, can we change iterators value inside for loop

Python loop for iterator following is code snippet sum = 0 for i in range(10): i = I + 3 sum += 3 print (sum) It sums up the 10 number from offset 3 Why it's not affect the updation of iterator to loop for lesser number of iterations since I is updated by adding three(3) Answer: 75 3 + 4 + 5 + ... + 12 = 75

16th Mar 2021, 5:32 AM
DHANANJAY PATEL
DHANANJAY PATEL - avatar
5 ответов
+ 1
idk much about python but u can think it like this if u do list instead of range eg: a = [2, 3, 2 ,3] for i in a: print(i) what u print is the value of list in each iteration(i = a[currentindex]) so even if u increase i inside the loop, the index still not change, cause i is the value of the range im not good at explaining but hope u understand what i mean
16th Mar 2021, 5:40 AM
durian
durian - avatar
+ 1
i dont really know..but since list(range(10)) return that, probably..let just hope some python expert to answer and clear this thing up for us😂
16th Mar 2021, 5:50 AM
durian
durian - avatar
+ 1
yes, range return a list (a generator in python3+) and you iterate over values: that's why changing 'iterator' variable (i) inside the loop has no effect on next iteration ;)
16th Mar 2021, 7:50 AM
visph
visph - avatar
+ 1
Thanks Looks like it is a new one
16th Mar 2021, 4:53 PM
DHANANJAY PATEL
DHANANJAY PATEL - avatar
0
Lily Mea Thanks for quick reply can I assume that range(10) as [0,1,2,3,4,5,6,7,8,9] list DHANANJAY
16th Mar 2021, 5:46 AM
DHANANJAY PATEL
DHANANJAY PATEL - avatar