18

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?

2
  • 1
    Interesting related question: Tuple or list when using 'in' in an 'if' clause?. Goes into some detail about what CPython does under the hood. Commented 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? Commented Mar 21, 2016 at 12:06

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.