Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a function in a for loop called multiple times?

Tags:

python

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  
like image 722
Shynras Avatar asked Nov 17 '25 04:11

Shynras


1 Answers

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 ...
like image 111
iBug Avatar answered Nov 19 '25 19:11

iBug