[Tutor] Tuple - Immutable ?

col speed ajarncolin at gmail.com
Thu Mar 8 12:57:14 CET 2012


On 8 March 2012 18:51, Steven D'Aprano <steve at pearwood.info> wrote:
> 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
Because it's on the same line and there are 2 variables with the same
int, it gets cached???
Otherwise I'm truly boggled(a normal state of mind for me).


More information about the Tutor mailing list