samuelbrody1249
samuelbrody1249

Reputation: 4767

Does python cache or recalculate a function call on a while loop operation

Given the following:

s = '1234567'
i = 0
while (i < len(s)):
    i += 1

Does python recalculate the len(s) on every loop, or does it only calculate it once? In other words, should I move the len(s) above into a variable above the loop or is it fine where it is?

Upvotes: 3

Views: 1531

Answers (3)

Yasa Zaheen
Yasa Zaheen

Reputation: 11

it recalculates

len(s)

because the while loop needs to check on each iteration if its condition or conditions are True.

Upvotes: 0

wim
wim

Reputation: 362796

Python will not cache the value in any way. len(s) will be called on every iteration.

In such looping constructs, there's no point to create a separate variable to store a length, since the calculation is fast for all built-in container types. Doing so would be called a premature optimization.

Upvotes: 2

falsetru
falsetru

Reputation: 369134

https://docs.python.org/3/reference/compound_stmts.html#the-while-statement

while_stmt ::=  "while" assignment_expression ":" suite
               ["else" ":" suite]

This repeatedly tests the expression and, if it is true, executes the first suite;

By replacing len with customer length function, you can verify the behavior.

>>> def mylen(s):
...     print('mylen called')
...     return len(s)
... 
>>> s = '1234567'                                                                                       
>>> i = 0 
>>> while i < mylen(s):
...     i += 1
... 
mylen called
mylen called
mylen called
mylen called
mylen called
mylen called
mylen called
mylen called

BTW, if you want to iterate the sequence (string, in this case) sequentially, why don't you use simple for loop.

If you really need to use index, you can use enumerate:

>>> for i, character in enumerate(s):
...     print(i, character)
... 
0 1
1 2
2 3
3 4
4 5
5 6
6 7

Upvotes: 3

Related Questions