Home > Net >  What to do if a variable is in the for loop statement?
What to do if a variable is in the for loop statement?

Time:06-22

I'm just wondering what would happen if a variable is the for loop (or while loop) statement. Will that variable only be evaluated the first time that statement is executed?
For example:

arr = [2, 3, 4]

for i in range(len(arr)):
    arr.append(5)

CodePudding user response:

Yes. Try it:

>>> arr = [2, 3, 4]
>>>
>>> for i in range(len(arr)):
...     arr.append(5)
...
>>> arr
[2, 3, 4, 5, 5, 5]

As you can see, the loop has 3 iterations, because that's the value of len(arr) at the start of the loop.

This is the exact reason that it's generally discouraged to modify a list (or any other iterable) as you're iterating over it; the results may not always be intuitive since the iterator is set up at the start of the loop, and modifying the list may cause it to behave in unexpected ways (skipping over items, etc).

CodePudding user response:

Will that variable only be evaluated the first time that statement is executed?

Yes, if I understand your question correctly, the expression in the header of the for loop is only evaluated once. You can verify this by creating your own function that prints a message then returns the length of the array.

def my_fun(my_list):
    print("Inside my function.")
    return len(my_list)

arr = [2, 3, 4]

for i in range(my_fun(arr)):
    arr.append(5)

print(arr)

Output:

Inside my function.
[2, 3, 4, 5, 5, 5]

As you can see, the message is only printed one time, so range(my_fun(arr)) must only be evaluated one time.

CodePudding user response:

The code here is equivalent to :

arr = [2, 3, 4]
r = range(len(arr))
for i in r:
    arr.append(5)
print(arr)

Here the call to the range function generates a new object of type range (https://docs.python.org/3/library/stdtypes.html#typesseq-range). The iteration through the for loop is therefore on the object r, and not on the object arr. The modification in the loop of arr has therefore no consequences on the loop itself, since this one is on the object r.

On the other hand, if we try the following code :

arr = [2, 3, 4]
for i in arr:
    arr.append(5)
    if len(arr) > 15:
        break
print(arr)

We get the following result:

[2, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]

Here the for loop is applied directly on arr, and so its modification does impact the iteration performed by the for.

  • Related