Q: Loop while checking if element in a list in Python 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?

A: 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.
