简体   繁体   中英

Why doesn't the value in for loop change?

Why does the value of range(len(whole)/2) not change after whole is modified? And what do you call range(len...) value in for-loop?

whole = 'selenium'
for i in range(len(whole)/2):
    print whole
    whole = whole[1:-1]

output:

selenium
eleniu
leni
en

The range() produces a list of integers once . That list is then iterated over by the for loop. It is not re-created each iteration; that'd be very inefficient.

You could use a while loop instead:

i = 0
while i < (len(whole) / 2):
    print whole
    whole = whole[1:-1]
    i += 1

the while condition is re-tested each loop iteration.

The range function creates a list

[0, 1, 2, 3]

And the for loop iterates over the value of the list.

The list is not recreated each and every time

But this is not the case in normal list

wq=[1,2,3]

for i in wq:
    if 3 in wq:
        wq.remove(3)
    print i

1
2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM