Explanation of list reference

Chris Angelico rosuav at gmail.com
Fri Feb 14 16:16:41 EST 2014


On Sat, Feb 15, 2014 at 7:58 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Say you write:
>
>    1 + 2
>
> You may not find it most intuitive to follow through the object
> instantiation and reference manipulation implicit in the "everything is
> a reference" model when you think you understand numbers but have little
> idea of memory, objects, heap, allocation etc.

I don't object to a bit of handwaving where it doesn't matter
(especially as regards language design versus language interpreter
design - I'll happily talk about "storing an object on the heap"
without going into the details of allocating memory, managing
reference counts, and so on; the details of how CPython goes about
storing stuff on the heap isn't particularly significant), but be
careful of simplifications that will cause problems down the line.
Distinguishing "small values" from "big values" leads to the obvious
question: Which is which? And why doesn't this work?

>>> x = 3000
>>> z = x
>>> z is x
True

Seems legit... you set z equal to x, and then z is the same as x.
Okay, let's try that slightly differently.

>>> x = 1000
>>> y = 2000
>>> z = x + y
>>> z is 3000
False

What's different? How come I can do comparisons with 'is' sometimes
but not other times? (And just to make things more confusing, if you
do this in CPython with small numbers, it'll *seem* to work.)

The only way to explain it thoroughly is to fully distinguish between
names and objects, and explain what assignment actually means. Then
it's obvious that, in the first case, the identity check passes, while
in the second case, it doesn't.

ChrisA



More information about the Python-list mailing list