Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is function called every time the for loop runs?

I have a very general doubt and can be applied to many scenarios, If I have a code like this

for val in arr.flatten():
   print(val)

Query

Is flatten() function called every time the for loop runs ?
If so, then above approach will be inefficient compared to this one

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

arr2 = arr.flatten()
for val in arr2:
   print(val)

>Solution :

The two examples are equivalent (aside from one additional local variable).

What happens in the first example is:

  1. arr.flatten() is called, and it returns an iterable (which isn’t bound to a name)
  2. for iterates over the returned iterable.

What happens in the second example is:

  1. arr.flatten() is called, and it returns an iterable, which is bound to the name arr2.
  2. for iterates over arr2.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading