why () is () and [] is [] work in other way?

Robert Kern robert.kern at gmail.com
Fri Apr 20 15:26:27 EDT 2012


On 4/20/12 8:10 PM, dmitrey wrote:
> I have spent some time searching for a bug in my code, it was due to
> different work of "is" with () and []:
>>>> () is ()
> True

The empty tuple is unique, immutable, and common so the Python runtime optimizes 
this by reusing the same object, much like small integers are interned. This is 
not something your code should rely on, though.

>>>> [] is []
> False

Empty lists are mutable and may be modified differently, so they cannot be the 
same object. Every time you use an empty list literal, it must create a new object.

> (Python 2.7.2+ (default, Oct  4 2011, 20:03:08)
> [GCC 4.6.1] )
>
> Is this what it should be or maybe yielding unified result is better?

If your code is relying on the difference, or a lack of one, it's buggy.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list