"At times" - yes. But even in very simple cases the difference can be quite large (20% difference when computing a list of squares from 0 to 100 [well 99]).
So it will basically replace every reference to the iteration variable by a load fast and the "load_name, load_method, ..., call_method, pop" sequence with a single list_append. There are of course cases where the difference doesn't end up being that big (e.g. simply modifying the example to instead only consider even values of x) - but in general it'd be stupid not to use it especially considering how it's also far more readable and concise.
I agree with the article if you are just doing a calculation and not saving the results to a list but the test they used to show a loop as faster then a comprehension they did nothing with the resulting value. I totally agree that if you don't need a list a list comprehension is definitely a better way to go. And numpy arrange and doing calculations on the resulting array is better.
But my argument was that a comprehension is faster when you need the values to be in a list. I think a more accurate test is just comparing a generator (range) with the for loop and append vs the comprehension with no calculation. In this base situation the comprehension is ~25% faster. There are situations where there are better tools for the job but when it is building a list from a generator and an np array isn't a point you can start at. I have not seen a situation where a loop is faster.
View all comments
Show parent comment
6
u/[deleted] May 01 '22 edited May 01 '22
Seems to be marginal improvement at times.
Comprehensions vs for loops, not what you think