newbie looking for help, int reference question

Andrew McGregor andrew at indranet.co.nz
Tue Jan 14 13:15:15 EST 2003


--On Tuesday, January 14, 2003 19:07:19 +0100 jodocus <johocus at zonnet.nl> 
wrote:

> hi,
>
> i am learning python, but at the moment i cannot afford to buy a book on
> the subject. So i am trying to find all the appropriate information on the
> web. This proves difficult, so if anyone knows a good (complete) online
> book/resource about the language, i would like to know. I am looking for
> more than just a tutorial (these are not hard to find), but rather a
> complete work that describes the details of the language.

The docs from the python source distribution are pretty complete.  Usually 
if you install binaries, there will be a documentation package along with 
them that contains these.

>
> A thing I just ran into and couldn't find in the tutorials i am using:
>
>>>> i = 10
>>>> j = i
>>>> i is j
> 1
>>>> i += 10
>>>> i
> 20
>>>> j
> 10
>
> it seems that, after adding a value, i has become another object. So i
> guess the + operator makes a new object, does this mean that ints are
> 'immutable'? How do i make sure that j changes when i does? Is this
> comparable to the Java distinction between objects and primitive types,
> where objects are referenced but primitives are not?

In python, every name is always a reference.  So yes, integers are 
immutable (it wouldn't be meaningful for 1 to suddenly behave as if it were 
2 :-)).

Each name is interpreted by searching for it in the set of in-scope 
namespaces, which are (effectively) dictionaries mapping from the name to 
whatever value is bound to that name.

Assignment is a statement (not an expression) which binds the name(s) on 
the LHS to the value(s) on the RHS.  The += forms mean the same as their 
expansion, so

i += 10

really is the same as

i = (i + 10)

and means 'rebind the name i to the object returned by the expression i + 
10'

If you want the value bound by two names to change in sync, it has to be a 
mutable container (dictionary, list, or class instance of some kind):

>>> i = [1]
>>> i
[1]
>>> j = i
>>> j
[1]
>>> i[0] = 10
>>> i
[10]
>>> j
[10]

i and j refer to the same object, a list.  Changing i[0] rebound the 0'th 
slot in the list, not either name.

> As a C/C++ programmer i really like to know whether i am dealing with
> pointers or not, this makes me feel more sure about the correctness of the
> code i am writing.

It's not really a case of pointers; conceptually name bindings are somewhat 
different.  But it is much more the case that 'names act like 
pointers-to-objects' than 'names act like C variables'.

Andrew

>
> Thanks a lot,
>
> R

You're welcome.





More information about the Python-list mailing list