I want to know if this loop call multiple times "hello".upper() (or any other method/function) while iterating:
for i in "hello".upper():
#DO SOMETHING
Considering that "hello" doesn't change in the loop, would this be better performance wise?:
string = "hello".upper()
for i in string:
#DO SOMETHING
The loop target is evaluated only once, after which an iterator is obtained. Then, next() on that iterator is called for every iteration of the loop.
You can think of for a in b as:
_iter = iter(b) # Evaluates b only ONCE
while True:
try:
a = next(_iter)
except StopIteration:
break
# loop body ...
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