简体   繁体   中英

Is a function in a for loop called multiple times?

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 ...

The argument to the for statement is evaluated once. So it won't be executed multiple times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM