dis.dis lets you look at the operations Python performs when evaluating each expression:
In [57]: dis.dis(lambda: [0.5]*100000)
1 0 LOAD_CONST 1 (0.5)
3 BUILD_LIST 1
6 LOAD_CONST 2 (100000)
9 BINARY_MULTIPLY
10 RETURN_VALUE
In [58]: dis.dis(lambda: [0.5 for i in range(100000)])
1 0 BUILD_LIST 0
3 LOAD_GLOBAL 0 (range)
6 LOAD_CONST 1 (100000)
9 CALL_FUNCTION 1
12 GET_ITER
>> 13 FOR_ITER 12 (to 28)
16 STORE_FAST 0 (i)
19 LOAD_CONST 2 (0.5)
22 LIST_APPEND 2
25 JUMP_ABSOLUTE 13
>> 28 RETURN_VALUE
The list comprehension is performing a loop, loading the constant 0.5
each time, and appending it to a result list.
The expression [0.5]*100000
requires only one BINARY_MULTIPLY.
Also note that [obj]*N
makes a list of length N
, with N
reference to the exact same obj
.
The list comprehension [expr for i in range(N)]
evaluates expr
N
times -- even if expr
evaluates to the same value each time.