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)
Answers:
The two examples are equivalent (aside from one additional local variable).
What happens in the first example is:
arr.flatten()
is called, and it returns an iterable (which isn’t bound to a name)
for
iterates over the returned iterable.
What happens in the second example is:
arr.flatten()
is called, and it returns an iterable, which is bound to the name arr2
.
for
iterates over arr2
.
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)
The two examples are equivalent (aside from one additional local variable).
What happens in the first example is:
arr.flatten()
is called, and it returns an iterable (which isn’t bound to a name)for
iterates over the returned iterable.
What happens in the second example is:
arr.flatten()
is called, and it returns an iterable, which is bound to the namearr2
.for
iterates overarr2
.