Is function called every time the for loop runs?

Question:

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

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

||

Answers:

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.
Answered By: AKX
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.