A list comprehension will faster when creating lists. When I was new to python I didn’t like reading them so I tended to use loops instead.
I got better at writing code now they aren’t Intimidating. But I imagine this is like that, if you are new comprehensions aren’t the most intuitive structure to read.
"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.
I think it is more because it is a purpose built structure. If you look at SV-97's comment on the other reply to my comment they provided some byte code generated by the python interpreter for a loop vs a comprehension.
View all comments
Show parent comment
50
u/Sentie_Rotante Apr 30 '22
A list comprehension will faster when creating lists. When I was new to python I didn’t like reading them so I tended to use loops instead.
I got better at writing code now they aren’t Intimidating. But I imagine this is like that, if you are new comprehensions aren’t the most intuitive structure to read.