tuple of ids of integers or lists

Roy Smith roy at panix.com
Sun Mar 17 15:59:17 EDT 2013


In article <8e66719c-5e90-4776-bba9-a11c29fba2f1 at googlegroups.com>,
 bartolome.sintes at gmail.com wrote:

> In Python 3.3 for Windows, every list gets a different id when it is created:
> 
> >>> id([3])
> 46555784
> >>> id([3])
> 47920192
> >>> id([4])
> 46532048
> 
> But if I write a tuple asking for the ids of two lists, each list seems to 
> get the same id:
> 
> >>> id([3]), id([4])
> (43079000, 43079000)
> 
> I was expecting a tuple with two different ids. What is the reason for this 
> behaviour?

This is a classic little gotcha.

Object ids are guaranteed to be unique, but only for the lifetime of an 
object.  Or, to put it another way, it is guaranteed that no two objects 
that exist at the same time can have the same id.

What's happening when you do:

>>> id([3]), id([4])

Is that a list, [3], is created, its id is taken, and then the list is 
destroyed.  In this particular implementation, object ids happen to be 
the address of the object in memory.  Then, a new list, [4], is created.  
It just so happens that it gets created using the same memory block that 
was just freed by the destruction of the other list, so it ends up in 
the same place in memory.  So it gets the same id!

Kind of neat, huh?

PS -- this makes a nice interview question to see if somebody really 
understands what's happening beneath the surface.



More information about the Python-list mailing list