3

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?

1
  • 1
    Iteration is preferred to indexing. If you plan to s[i] with that index, then for c in s: and never checking length would likely be better. Commented Mar 24, 2020 at 4:36

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

I'm not sure replacing built-in len with mylen is a very convincing argument. Users coming from other languages, where compiler optimizations are able to do much more than is possible in Python, might reasonably expect a builtin length call on an immutable object to get optimized.
@wim, I'm not saying OP should save the result of len(...). I wanted to show Python behavior. :)
Sorry, maybe I didn't explain well - my point was that CPython might be clever enough to see that the values of s and len are not changing using a static analysis at compile time. In reality it does not bother, of course, but that would be conceivable for developers more familiar with languages that have farther reaching compiler optimizations. And it's something that would obviously not be tractable with an arbitrary user-defined function in place of the built-in len.
2

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.

Comments

0

it recalculates

len(s)

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.