[Tutor] Follow-up Qs: Re: Identity operator (basic types)

Alan Gauld alan.gauld at btinternet.com
Mon Feb 12 02:06:54 CET 2007

"Cecilia Alm" <ebbaalm at uiuc.edu> wrote

> When we copy any such data type (float, integer, string, char, bool) 
> into a
> function definition's local scope, does it always copy-by-value 
> then?

Kent has already answered this but no. we never copy by value
in Python, we create a new reference to the value.

>>>> def sum(k):
>    print k, id(k)
>    k += 1

This is actually k = k + 1
So k now refers to a new value which is one more than the
original value.

>>>> a = 1234
>>>> print a, id(a)
> 1234 12536936
>>>> sum(a)

This sets k to point to the same value as a: 1234

> 1234 12536936
> 1235 12536876

k now refers to the new value 1235. But a still refers to its
original value:

>>>> print a, id(a)
> 1234 12536936

As seen here.

As Kent said, you need to change your way of thinking
about variables and values. In Python variables are just
names. In fact they are dictionary keys. You can even
print the dictionary if you want, its called locals.

>>> x = 42
>>> print locals()
{'__builtins__': <module '__builtin__' (built-in)>,
'x': 42,
'__name__': '__main__',
'__doc__': None}

Notice that my x appears in the second line...

But its still just a reference to the real object. If I added a
new line y = 42 there would still only be a single 42 object
and both x and y dictionary entries would point at it.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list