简体   繁体   中英

Is a function in a for loop declaration will be called for many times in Python?

There is a function and a for loop:

def helper():
    return [1,2,3]

for i in helper():
    print(i)

I am wondering if the helper function would only be called once at the initialization of the for loop. As I am thinking that if I call the function and assign the return array to a variable in advance, which would be used in the for loop like this:

def helper():
    return [1,2,3]
temp = helper()
for i in temp:
    print(i)

Is that with less time complexity?

Thanks!

use the yield operation:

def helper():
    for i in [1,2,3]:
         yield i

for i in helper():
    print(i)

in this case the helper() method would return the i value during each iteration to the calling for loop.

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