[Tutor] if n == 0 vs if not n

Kent Johnson kent37 at tds.net
Tue Oct 6 17:34:06 CEST 2009

On Tue, Oct 6, 2009 at 11:08 AM, Wayne <srilyk at gmail.com> wrote:
> On Tue, Oct 6, 2009 at 9:58 AM, Dave Angel <davea at ieee.org> wrote:
>> <snip>
>> No, because you're not assured that all integers that are equal are the
>> same object.  Python optimizes that for small integers, but there's no
>> documented range that you can count on it.
> But for this specific case - checking a return code against zero, should it
> still be considered unreliable?

Yes. It is undocumented, implementation-specific behaviour and you
should not depend on it without good reason. In this case, there is no
reason at all to prefer "if x is 0" to "if x == 0".

> The only case that you are looking for
> correctness is 0 == 0, any other case should evaluate as false, so I guess
> the question is does python always optimize for zero? Any other optimization
> is irrelevant, AFAIK.

Define "always". In all past and future versions of every
implementation of Python? Unlikely and unknowable. In all current
versions of CPython? Yes, AFAIK.


More information about the Tutor mailing list