[Tutor] Tuple - Immutable ?

Steven D'Aprano steve at pearwood.info
Thu Mar 8 12:51:33 CET 2012


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.)



-- 
Steven



More information about the Tutor mailing list