Removing None objects from a sequence

Raymond Hettinger python at rcn.com
Fri Dec 19 06:42:24 EST 2008


On Dec 12, 7:51 am, Marco Mariani <ma... at sferacarta.com> wrote:
> Filip Gruszczyński wrote:
> > I am not doing it, because I need it. I can as well use "if not elem
> > is None",
>
> I suggest "if elem is not None", which is not quite the same.

They are semantically the same.  In theory, Filip's would run slower
because of the time to negate the is-test, but the peephole optimizer
recognizes the opportunity to make the substitution so it works out
exactly the same:


>>> dis(compile('x is not None', '', 'eval'))
  1           0 LOAD_NAME                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE
>>> dis(compile('not x is None', '', 'eval'))
  1           0 LOAD_NAME                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE

Raymond



More information about the Python-list mailing list