简体   繁体   中英

Will the function in python for loop be executed multiple times?

Say I have the following class with a method returning a list:

Class C():
  def f():
    return [1,2,3]

If I loop over the this method as follows:

c=C()
for i in c.f():
  print i

Inside the for loop, will cf() be executed multiple times? If yes, in order to get it once, do I have to do assignment outside of the loop, or there is some trivial way?

In [395]: def tester():
     ...:     print "Tester Called!"
     ...:     return [1,2,3]

In [396]: for i in tester():
     ...:     pass
Tester Called!

Seems the answer is no.

cf() will not get executed multiple times.

You didn't ask, but you might be curious about generators .

Your example as a generator would be as follows:

Class C():
  def f():
    yield 1
    yield 2
    yield 3

The loop where you iterate over the results would be unchanged.

from the python docs :

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:

 for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] 

The expression list is evaluated once ; it should yield an iterable object.

No it is executed once .

And your method is not correctly defined. Should have a self argument:

class C:
  def f(self):
    return [1,2,3]

It will be executed only once. But there will be syntax errors in your code:

class , not Class
def f(self) , not def f()

Did you try to test it yourself? The answer to your question is NO.

Here is how you should have tested it. Moreover there were lot of flaws in your code. Check the self commented modified version below

>>> class C: #its class not Class and C not C()
    def f(self): #You were missing the self argument
        print "in f" #Simple Test to validate your query
        return [1,2,3]


>>> c=C()
>>> for i in c.f():
    print i


in f
1
2
3
>>> 

Though this example is trivial but still I will use this as an example to explain how we can leverage the power of functional programming of Python. What I will try to explain is called lazy evaluation or generator functions(http://docs.python.org/glossary.html#term-generator).

Consider the modified example

>>> class C: #its class not Class and C not C()
    def f(self): #You were missing the self argument
        print "in f" #Simple Test to validate your query
        for i in [1,2,3]:
            yield i #Generates the next value when ever it is requsted
        return #Exits the Generator


>>> c=C()
>>> for i in c.f():
    print i


in f
1
2
3
>>> 

Can you spot the difference?

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