Python modify range variable in for loop
# Python modify range variable in for loop
When I want to done a job like below, I noticed that python doesn't support modify range variable like java or c code.
# It supposed to be infinity loop
for i in range(5):
print('i:', i)
i-=1
'''
output:
i: 0
i: 1
i: 2
i: 3
i: 4
'''
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
The reason it Python doesn't care about the current value of i. It runs like linked list, and using next to iterate and finish the loop. Thus, this method doesn't support by Python. To do something like that, we can use a while loop like below.
i = 0
while (i < 5):
print('i:',i)
i+=1
if (i==2):
i+=2
'''
output:
i: 0
i: 1
i: 4
'''
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
Updated: 2021/09/05, 15:42:35