by simonw · 10y ago · 0 comments
You can actually get a very good idea for what Python is doing under the hood using the dis module:
dis.dis(lambda: 1 <= len(vals) <= 5)
1 0 LOAD_CONST 1 (1)
3 LOAD_GLOBAL 0 (len)
6 LOAD_GLOBAL 1 (vals)
9 CALL_FUNCTION 1
12 DUP_TOP
13 ROT_THREE
14 COMPARE_OP 1 (<=)
17 JUMP_IF_FALSE_OR_POP 27
20 LOAD_CONST 2 (5)
23 COMPARE_OP 1 (<=)
26 RETURN_VALUE
>> 27 ROT_TWO
28 POP_TOP
29 RETURN_VALUE
Compare to: dis.dis(lambda: len(vals) in range(1, 5))
1 0 LOAD_GLOBAL 0 (len)
3 LOAD_GLOBAL 1 (vals)
6 CALL_FUNCTION 1
9 LOAD_GLOBAL 2 (range)
12 LOAD_CONST 1 (1)
15 LOAD_CONST 2 (5)
18 CALL_FUNCTION 2
21 COMPARE_OP 6 (in)
24 RETURN_VALUE $> python -m timeit "1 <= 4 <= 5"
10000000 loops, best of 3: 0.0877 usec per loop
$> python -m timeit "4 in range(1,5)"
1000000 loops, best of 3: 0.413 usec per loop
$> python -m timeit "4 in (1,2,3,4,5)"
10000000 loops, best of 3: 0.0776 usec per loop
Tested in python 3.5.0, Even with the improvements to the range function, the comparison is almost 5x faster.This output doesn't really provide any clarification.
You have two function calls in the range version and only one in the non-range version. You are just hiding some of that code in a dynamic function call. Also, your compare_op consists of two <= in the non-range version and an "in" compare_op for the range version (which probably hides the element by element comparison or hash/bloom if it is O(1).
Fewer lines of code does not mean more efficient. Regardless of whether it is source code or bytecode.
It appears to me they went ahead and posted the bytecode for both because they had spun up an interpreter to get the bytecode for one.