tuple of ids of integers or lists

Chris Angelico rosuav at gmail.com
Sun Mar 17 16:34:51 EDT 2013


On Mon, Mar 18, 2013 at 7:23 AM,  <bartolome.sintes at gmail.com> wrote:
> OK. Now I understand it.
>
> I was confused because when two list are created in two different lines, Python gives them different ids, but when the two lists are created in the same line (in a tuple) Python gives them the same id. It doesn't really matter as these lists are just created and destroyed, as you have said.
>
> Thank you very much for your fast answer.

Here's something that'll either help you understand another aspect of
Python, or totally do your head in.

>>> print(id([3]))
14485504
>>> print(id([3]))
14485504

If you print it to stdout, the id can be reused! How is this?

Here's what's going on. In interactive mode, the result of the last
expression is made available under the name _ (a single underscore):

>>> id([3])
15597160
>>> _
15597160

Integers are objects, like everything else. (Some of them are
pre-made, but big numbers like this aren't - at least, not in this
Python. But that's implementation-dependent too.) The retention of
this integer object can in some circumstances change where the next
object is stored. So you may find that some things behave differently
in interactive mode than in a script; or perhaps printing something
out instead of letting the interpreter display it will change what
happens.

You're looking into some extremely unspecified behaviour, here, so
anything is allowed to affect it. Which means you might be able to
learn all sorts of things about Python's internals! :)

ChrisA



More information about the Python-list mailing list