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

Dave Angel d at davea.name
Sat Apr 21 00:32:59 EDT 2012


On 04/20/2012 11:25 PM, Rotwang wrote:
> On 21/04/2012 01:01, Roy Smith wrote:
>> In article<877gxajit0.fsf at dpt-info.u-strasbg.fr>,
>>   Alain Ketterlin<alain at dpt-info.u-strasbg.fr>  wrote:
>>
>>> Tuples are immutable, while lists are not.
>>
>> If you really want to have fun, consider this classic paradox:
>>
>>>>> [] is []
>> False
>>>>> id([]) == id([])
>> True
>
> Huh. This is not what I would have expected. What gives?
>

It'd be easier to respond if you would say what's confusing to you about
that result.  The first is exactly what I'd expect, and the second is
implementation dependent.

[] is [] produces two independent lists, then compares their ID, then
discards them.  So of course they must be different.

id([]) prepares a list object and figures out its id.  Then discards the
object.   You do it a second time, and you *might* get a new object with
the same id.  After all, the first one is gone now, so there's no harm
in re-using the id.  In particular, the CPython implementation currently
uses the address of the object as the ID, so if the memory is available,
the next allocation just might get the same memory.

Remember that the only guarantee on id() is that it won't assign the
same number to two objects that exist at the same time.  Once an object
is gone, its ID may be reused right away, or after a while, or never.

-- 

DaveA




More information about the Python-list mailing list