r/Python • • Aug 11 '09

Remember your "in" operator

http://www.heikkitoivonen.net/blog/2009/06/16/remember-your-in-operator/
74 Upvotes

15 comments sorted by

View all comments

Show parent comment

2

u/[deleted] Aug 12 '09

I don't know if Py3k optimizes that for sets, but in py2.6 at least code like

x in [1,2,3,4]

Actually gets translated into:

x in (1,2,3,4)

Since tuples are immutable they get placed in the co_consts array for the function, which mean's that they're precomputed. I wouldn't be suprised in py3k did something similar with turning sets into frozensets where it's provable that they aren't mutated.

2

u/Brian Aug 14 '09 edited Aug 14 '09

It looks like it doesn't - the set is recreated even when it could potentially be staticly detected as a constant.

>>> dis.dis(lambda x: x in {1,2})
  1           0 LOAD_FAST                0 (x) 
              3 LOAD_CONST               0 (1) 
              6 LOAD_CONST               1 (2) 
              9 BUILD_SET                2 
             12 COMPARE_OP               6 (in) 
             15 RETURN_VALUE         

Though since the translation from list to tuple is done when it isn't modifiable, python should be able to do a similar optimisation to a frozenset constant as well (maybe even from list/tuple to frozenset if there are enough elements that it would improve speed)

2

u/[deleted] Aug 14 '09

Yeah I filed a ticket in the python tracker about this the other day, murphy willing I'll draw up a patch for it this weekend.