Removing None objects from a sequence

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Dec 12 17:40:39 EST 2008


On Fri, 12 Dec 2008 10:08:23 -0600, Kirk Strauser wrote:

> At 2008-12-12T15:51:15Z, Marco Mariani <marco at sferacarta.com> writes:
> 
>> 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.
> 
> So what's the difference exactly?  "foo is not None" is actually
> surprising to me, since "not None" is True.  "0 is True" is False, but
> "0 is not None" is True.  Why is that?

"a is not b" uses a single operator to do the test.

>>> import dis
>>> x = compile('a is not b', '', 'single')
>>> dis.dis(x)
  1           0 LOAD_NAME                0 (a)
              3 LOAD_NAME                1 (b)
              6 COMPARE_OP               9 (is not)
              9 PRINT_EXPR
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE


"not a is b" looks like it would use two operators (is, followed by not) 
but wonderfully, Python has a peephole optimization that fixes that micro 
inefficiency: 


>>> x = compile('not a is b', '', 'single')
>>> dis.dis(x)
  1           0 LOAD_NAME                0 (a)
              3 LOAD_NAME                1 (b)
              6 COMPARE_OP               9 (is not)
              9 PRINT_EXPR
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE



So if you are using at least Python 2.5, the two expressions don't just 
return the same result, they actually generate the same byte code.


-- 
Steven



More information about the Python-list mailing list