I'm coming from Tcl-world ...

Andrae Muys amuys at shortech.com.au
Wed Aug 7 03:13:12 CEST 2002


Andreas.Leitgeb at siemens.at (Andreas Leitgeb) wrote in message news:<slrnakt7gd.c05.Andreas.Leitgeb at pc7499.gud.siemens.at>...
> Meanwhile I've recognized Python's "call-by-ref" to be similar to
> Java's (probably because object-handling is similar between these
> languages)  and I can live with that. 
> 
> Generally:
>   It depends on the context on whether it is better to 
>   make use of call-by-ref or return a result.
> If the object is a list of millions of entries, it is definitely
>  better to have a way of modifying the list in-place than returning 
>  even a shallow copy of it.

I'm not certain, but this is the second time you seem to have implied
that passing/returning a list to/from a function involves a copy.  If
I'm mistaken please accept my appologies, however if I'm not you need
to be aware that this is not the case.

>>> l = [1,2,3]
>>> id(l)
10217196
>>> def dubtuple(p):
	return (p,p)

>>> t = dubtuple(l)
>>> id(t)
10169092
>>> id(t[0]),id(t[1])
(10217196, 10217196)
>>> l2 = l[:]
>>> id(l),id(l2)
(10217196, 10272260)

Note that there are only two lists in this example, one with id
10217196 and another with id 10272260.  Also note that at the end of
the example there are 3 references to the first list, and only 1 to
the second.  This has important ramifications.  First the value is
only ever copied explicitly at your request.  Second mutating the
first list affects the value percieved from all three of its bindings.

>>> t
([1, 2, 3], [1, 2, 3])
>>> l[1] = 4
>>> t
([1, 4, 3], [1, 4, 3])

Forgetting this is a common newbie mistake.

In general it is unhelpful to think of the "=" operator as
'assignment' because it isn't.  Much better to refer to it as binding,
as in 'creating a binding in a namespace'.

Andrae Muys



More information about the Python-list mailing list