Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 c.f() 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?

like image 342
Hailiang Zhang Avatar asked Dec 03 '11 16:12

Hailiang Zhang


1 Answers

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.

like image 63
Derek Litz Avatar answered Oct 26 '22 23:10

Derek Litz