3

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

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.