While I was reading and searching about what exactly causes performance difference between loops and list comprehension (based on below simple test cases, list comprehension faster), I encountered following posts here in SO:
Simple test cases:
def f1():
t = []
for i in range(10000):
t.append(i)
def f2():
t = [i for i in range(10000)]
Why is a list comprehension so much faster than appending to a list?
Are list-comprehensions and functional functions faster than “for loops”?
What I understand from above posts that main differences as follows;
- For loop builds a list but, list comprehension does not
- For loop loads append method on each iteration but, list comprehension does not
Then I used disassembler to see the details and I saw the below steps for following block of code:
Code:
def f2():
t = [i for i in range(10000)]
dis.dis(f2)
Disassembler result:
0 BUILD_LIST
2 LOAD_FAST
4 FOR_ITER
6 STORE_FAST
8 LOAD_FAST
10 LIST_APPEND
12 JUMP_ABSOLUTE
14 RETURN_VALUE
Based on Python doc; 0 BUILD_LIST
creates list and 10 LIST_APPEND
uses append method by contrast with above related posts:
LIST_APPEND(i)
Calls list.append(TOS[-i], TOS). Used to implement list comprehensions.
BUILD_LIST(count)
Works as BUILD_TUPLE, but creates a list.
I could not figure out what I am missing here. Is the way list comprehension builds and appends different than for loop, because anyway LIST_APPEND
contains append
method and BUILD_LIST
creates a list? or maybe the reason for the performance difference is something else? Can someone please clarify this for me?
Thanks a lot!