I often run into this situation while coding in Python, and am not sure which is more performant. Suppose I have a list l = [3, 13, 6, 8, 9, 53]
, and I want to use a list comprehension to create a new list that subtracts off the minimum value so that the lowest number is zero. I could do:
[x - min(l) for x in l]
On the other hand, I could do:
min_val = min(l)
[x - min_val for x in l]
Is it true that the first option causes min(l)
to run for every new item in the list, while the second option only calculates the minimum value once? Potentially, if l
is a very long list, this could be a significant performance difference? On the other hand, perhaps with a shorter list, the creation of a variable in option 2 results in some overhead?
I guess my question is: how much of a difference does this make? I find the first option cleaner and more compact, but don't know if that comes at a performance cost.
Relatedly, is there any performance difference between:
new_list = []
for x in l:
new_list.append(x ** 2)
and:
new_list = [x ** 2 for x in l]
Does the latter directly translate into the former, or is there a difference in what goes on under the hood?