Style question (Poll)

Prasad, Ramit ramit.prasad at jpmorgan.com
Wed Mar 14 18:15:38 EDT 2012


> >> Which is preferred:
> >>
> >> for value in list:
> >>   if not value is another_value:
> >>     value.do_something()
> >>     break
> 
> Do you really mean 'is' or '=='?

Let me expound on how 'is' and '==' are very different. It may work 
for some comparisons but often not for others. Certain examples work
because of the Python implementation. 

>>> c = 1
>>> d = 1
>>> c is d # This only works because CPython caches small values.
True
>>> c == d
True
>>> a = 10000000000000
>>> b = 10000000000000
>>> a is b
False
>>> a == b
True
>>> 10000000000000 is 10000000000000 
True

'10000000000000 is 10000000000000' works because the interpreter caches
the number because it is on the same line.


Only use 'is' if you are looking for objects like True,
False, None or something that MUST be exactly the same object.

In general, use '=='.



Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  



More information about the Python-list mailing list