- 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
5 odpowiedzi
+ 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
+ 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😂
+ 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 ;)
+ 1
Thanks
Looks like it is a new one
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