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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With