Difference between 'is' and '=='

Joel Hedlund joel.hedlund at gmail.com
Tue Mar 28 12:12:52 CEST 2006

> a is None
> is quicker than
> a == None

I think it's not such a good idea to focus on speed gains here, since they 
really are marginal (max 2 seconds total after 10000000 comparisons):

 >>> import timeit
 >>> print timeit.Timer("a == None", "a = 1").timeit(int(1e7))
 >>> print timeit.Timer("a == None", "a = None").timeit(int(1e7))
 >>> print timeit.Timer("a is None", "a = 1").timeit(int(1e7))
 >>> print timeit.Timer("a is None", "a = None").timeit(int(1e7))

Your observation is certainly correct, but I think it's better applied to more 
complex comparisons (say for example comparisons between gigantic objects or 
objects where value equality determination require a lot of nontrivial 
computations). That's where any real speed gains can be found. PEP8 tells me 
it's better style to write "a is None" and that's good enough for me. Otherwise 
I try to stay away from speed microoptimisations as much as possible since it 
generally results in less readable code, which in turn often results in an 
overall speed loss because code maintenance will be harder.

/Joel Hedlund

More information about the Python-list mailing list