Tuesday, 15 January 2013

for loop - Does iterating over returned data call the function every time in Python? -



for loop - Does iterating over returned data call the function every time in Python? -

def some_function(): # homecoming iterable_data datum in some_function(): #

here iterable_data may list, dictionary, etc.

so, for-loop calls some_function() every time looks next element of returned iterable_data?

no, look list executed just once. for compound statement documentation:

the look list evaluated once; should yield iterable object. iterator created result of expression_list. suite executed 1 time each item provided iterator, in order of ascending indices.

emphasis mine.

you can test yourself:

>>> def some_function(): ... print "some_function called" ... homecoming ['foo', 'bar', 'baz'] ... >>> datum in some_function(): ... print datum ... some_function called foo bar baz

the "some_function called" text printed once, not 3 times.

python for-loop

No comments:

Post a Comment