[Tutor] Tuple - Immutable ?
John Jensen
jensenjohn59 at yahoo.com
Thu Mar 8 13:18:51 CET 2012
________________________________
From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Sent: Thursday, March 8, 2012 7:51:33 AM
Subject: Re: [Tutor] Tuple - Immutable ?
col speed wrote:
> I was just thinking about the immutability of things and tried this
> (which -at least I- find interesting:
>
>>>> id(1)
> 154579120
>>>> a = 1
>>>> id(a)
> 154579120
>>>> a += 2
>>>> id(a)
> 154579096
>>>> id(3)
> 154579096
>>>> a is 3
> True
> Although there is probably no other logical way of doing it - I learnt
> something new again!
Prepare to have your mind boggled:
py> a = 99
py> b = 99
py> a is b
True
py> a = 9912345
py> b = 9912345
py> a is b
False
Well, okay, so it's not *much* of a boggle. Perhaps a bogglet.
What happens is that Python caches the small integers, like -1, 0, 1, up to some limit, and re-uses them when and as needed. That limit various from version to version, so you can't rely on it. But larger integers are not cached, and so you get a fresh one each time.
This makes sense, and is easy to understand. Now for the real boggle:
py> a = 9912346; b = 9912346
py> a is b
True
Can you guess what is going on here?
(Answer will follow later.)
I'll preface my answer by stating that I'm a noob and haven't checked the documentation for my answer, but I would guess that Python is saving the variables as integer values and that the larger values would require them being saved as doubles.
-- Steven
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120308/b0b9df4e/attachment.html>
More information about the Tutor
mailing list