negative numbers are not equal...
Dan Lenski
dlenski at gmail.com
Fri Aug 15 16:52:36 EDT 2008
On Fri, 15 Aug 2008 08:03:23 -0700, Carl Banks wrote:
> On Aug 14, 4:42 pm, Christian Heimes <li... at cheimes.de> wrote:
>> Integers
>> between -5 and +256 are singletons as are some other objects like
>> strings with one element or empty tuples.
>
> Not quite.
>
> Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian
> 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for
> more information.
>>>> a = 'A'
>>>> b = "%c" % a
>>>> a
> 'A'
>>>> b
> 'A'
>>>> a is b
> False
Wow... wow wow. How very odd. That is one exception I did not expect,
especially considering that string-formatting with a *literal* rather
than a variable gives the opposite result.
>>>> a = 'A'
>>>> b = "%c" % 'A'
>>>> a
> 'A'
>>>> b
> 'A'
>>>> a is b
> True
>> You must not rely on the
>> optimization.
>
> Good advice.
Indeed! Corner cases like the above will bit you in the ass ;-)
Simple rule of thumb: use "is" when you really truly want to check if two
symbols refer to the same object in memory. If that's not what you
*really* want to do, then don't use it!
Dan
More information about the Python-list
mailing list