This question already has an answer here:
- Python list comprehension expensive 1 answer
I was wondering why list comprehension is so much faster than appending to a list. I thought the difference is just expressive, but it's not.
>>> import timeit
>>> timeit.timeit(stmt='''\
t = []
for i in range(10000):
t.append(i)''', number=10000)
9.467898777974142
>>> timeit.timeit(stmt='t= [i for i in range(10000)]', number=10000)
4.1138417314859
The list comprehension is 50% faster. Why?
Citing this article, it is because the
append
attribute of thelist
isn't looked up, loaded and called as a function, which takes time and that adds up over iterations.List comprehension is basically just a "syntactic sugar" for the regular
for
loop. In this case the reason that it performs better is because it doesn't need to load the append attribute of the list and call it as a function at each iteration. In other words and in general, list comprehensions perform faster because suspending and resuming a function's frame, or multiple functions in other cases, is slower than creating a list on demand.Consider the following examples :
You can see at offset 22 we have an
append
attribute in first function since we don't have such thing in second function using list comprehension. All those extra bytecodes will make the appending approach slower. Also note that you'll also have theappend
attribute loading in each iteration which makes your code takes approximately 2 time slower than the second function using list comprehension.Even factoring out the time it takes to lookup and load the
append
function, the list comprehension is still faster because the list is created in C, rather than built up one item at a time in Python.