a = b = 1 just syntactic sugar?

Robin Munn rmunn at pobox.com
Wed Jun 4 11:40:37 EDT 2003


Peter Hansen <peter at engcorp.com> wrote:
> Asun Friere wrote:
>> 
>> "Batista, Facundo" <FBatista at uniFON.com.ar> wrote in message news:<mailman.1054662726.12651.python-list at python.org>...
>> 
>> > "b = 1" does not return 1, just returns b. a and b are the same object now
>> > (they are not just equal, they are the very same).
>> >
>> They are, but this has little to do with the fact that both assigned
>> their values using a single statement. ie:
>> >>>sys.ps1 = '? '
>> ? a = 1
>> ? b = 1
>> ? a is b
>> 1
> 
> Actually it has _everything_ to do with the mechanism by which your 
> example would produce a result of 1 except with low integers.
> 
> The interpreter pre-constructs and caches all the integers from -1 (?)
> to 100 (or maybe it's from 0 to 100... whatever) and always reuses them
> instead of creating new objects with the same integer values.  Try this:
> 
>>>> a = 556
>>>> b = 556
>>>> a is b
> 0
>>>> a = b = 556
>>>> a is b
> 1

Correct. Small integers and short strings both get cached for
performance reasons. Small integers in particular are likely to be used
over and over (especially the numbers 1 and 0). If you really want to
test the effects of assignment on identity, use a mutable type like
lists.

=== Begin Python transcript ===
>>> a = b = []
>>> a
[]
>>> b
[]
>>> id(a)
135714444
>>> id(b)
135714444
>>> a is b
1
>>> a = []
>>> b = []
>>> id(a)
135714732
>>> id(b)
135714508
>>> a is b
0
==== End Python transcript ====

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list