for a in sorted(arr):
doSomething()
vs
sArr = sorted(arr)
for a in sArr:
doSomething()
are those 2 are the same exactly, or will one consume more cpu cycles then the other?
meaning, will sorted(arr) gets called every loop in the first example?
thanks
They’re pretty much the same.
The documentation says:
So, there’s no risk of the
sorted()call happening more than once, in the above code.The first form is still better, since it’s shorter and more concise, and might make it possible to optimize better (since the intepreter could figure out that the sorted list goes totally out of scope after the loop finishes).