Will a function execute in a python loop for a loop multiple times?

Let's say I have the following class with a method that returns a list:

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

If I iterate over this method as follows:

 c=C() for i in cf(): print i 

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

+6
source share
6 answers
 In [395]: def tester(): ...: print "Tester Called!" ...: return [1,2,3] In [396]: for i in tester(): ...: pass Tester Called! 

The answer seems to be no.

+4
source

cf() will not execute multiple times.

You did not ask, but you may be interested to know generators .

Your example as a generator would look like this:

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

The cycle in which you iterate over the results will not change.

+3
source

from python docs :

The for statement is used to iterate over elements of a sequence (for example, a string, tuple or list) or another iterable object:

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

The list of expressions is evaluated once ; it should give an iterable object.

+3
source

No running .

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

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

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

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

+1
source

Have you tried to test this yourself? The answer to your question is NO.

This is how you should have tested it. In addition, there were many flaws in your code. Check out the modified version with comments 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 cf(): print i in f 1 2 3 >>> 

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

Consider a 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 cf(): print i in f 1 2 3 >>> 

Can you tell the difference?

+1
source

Source: https://habr.com/ru/post/903003/


All Articles