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)
>Solution :
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)foriterates 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.foriterates overarr2.