DEV Community

Jing Xue
Jing Xue

Posted on

List to Tuple: a Little Compilation Optimization

I was reading Julien Maury's Python pro tips, and ran into this code snippet:

if myvar in [9,1,7]

I was about to leave a comment to suggest using a tuple instead, because instinctively you would think tuples should be faster than lists, right?

if myvar in (9,1,7)

And then I decided not to trust my instinct and take a look at the bytecode first. Well, what do you know... both code compiles to exactly the same:

0 LOAD_FAST                0 (myvar)
2 LOAD_CONST               1 ((9, 1, 7))
4 COMPARE_OP               6 (in)

So the compiler is smart enough to realize that even though I am creating a mutable list, I won't actually make any changes to it, and will use it only once, so it converts the list to a tuple.

Taking one step further, I changed the code to:

l = [9, 1, 7]
if myvar in l

Now the compiler creates a list:

0 LOAD_CONST               1 (9)
2 LOAD_CONST               2 (1)
4 LOAD_CONST               3 (7)
6 BUILD_LIST               3
8 STORE_FAST               1 (l)

10 LOAD_FAST                0 (myvar)
12 LOAD_FAST                1 (l)
14 COMPARE_OP               6 (in)

Although I suppose one could argue that in this case the compiler should still have detected that l is never changed, and converted it to a tuple.

Top comments (0)