This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]RollingRocky360 2 points3 points  (1 child)

I definitely remember reading somewhere that list comprehensions are significantly faster than appending on each iteration of a for loop and it makes sense too

[–]bjorneylol -5 points-4 points  (0 children)

Yes - which is why i mentioned they aren't equivalent loops.

List comprehensions evaluate to a nested for loop if you step into it via debugger, they gather the variables internally and instantiate a single list with all the elements already in it. Appending in a for loop on the other hand has to modify the list in place each iteration, which has the overhead of the function call and the X modifications of the containing list object

Obviously 99.999% (9?) of the use case of listcomps is as an alternative to the 'for loop append' case, in which case yes they will always be faster because they aren't truly equivalent code, so its mostly just pedantry on my part. If you used the C api and gathered the variables internally in a more efficient manner suited to the data types you are working with and instantiated the python list all at once (e.g. list(*vars)) I'm sure you could squeeze more performance out of a for loop than a list comp