Let's say I have a simple piece of code like this:
for i in range(1000):
if i in [150, 300, 500, 750]:
print(i)
Does the list [150, 300, 500, 750] get created every iteration of the loop? Or can I assume that the interpreter (say, CPython 2.7) is smart enough to optimize this away?
asked Feb 24, 2016 at 15:13
Joohwan
2,5421 gold badge23 silver badges31 bronze badges
-
1Interesting related question: Tuple or list when using 'in' in an 'if' clause?. Goes into some detail about what CPython does under the hood.Kevin– Kevin2016年02月24日 15:43:49 +00:00Commented Feb 24, 2016 at 15:43
-
Unless you specify that you want to know about 1 specific interpreter, this is very difficult to answer. Can you rephrase "(say, CPython 2.7)" to specify you want to know about that interpreter exactly?Jon Surrell– Jon Surrell2016年03月21日 12:06:05 +00:00Commented Mar 21, 2016 at 12:06
1 Answer 1
You can view the bytecode using dis.dis. Here's the output for CPython 2.7.11:
2 0 SETUP_LOOP 40 (to 43)
3 LOAD_GLOBAL 0 (range)
6 LOAD_CONST 1 (1000)
9 CALL_FUNCTION 1
12 GET_ITER
>> 13 FOR_ITER 26 (to 42)
16 STORE_FAST 0 (i)
3 19 LOAD_FAST 0 (i)
22 LOAD_CONST 6 ((150, 300, 500, 750))
25 COMPARE_OP 6 (in)
28 POP_JUMP_IF_FALSE 13
4 31 LOAD_FAST 0 (i)
34 PRINT_ITEM
35 PRINT_NEWLINE
36 JUMP_ABSOLUTE 13
39 JUMP_ABSOLUTE 13
>> 42 POP_BLOCK
>> 43 LOAD_CONST 0 (None)
46 RETURN_VALUE
Hence, the list creation is optimized to the loading of a constant tuple (byte 22). The list (which is in reality a tuple in this case) is not created anew on each iteration.
answered Feb 24, 2016 at 15:16
arshajii
130k26 gold badges246 silver badges293 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
lang-py