Passing by value instead of reference
Michael Hudson
mwh21 at cam.ac.uk
Wed May 10 15:33:24 EDT 2000
"Jeff Massung" <jmassung at magpiesystems.com> writes:
> Michael Hudson wrote in message ...
> >It will. I don't think you understand assigment yet...
> >
>
> Sorry, I don't ;) - I was thinking like this (I understand how my previous
> example was wrong).
>
> >>> def test(x):
> x.append(3)
> >>> z = [1,2]
> >>> test(z)
> >>> z
> [1, 2, 3]
> >>>
>
> How can I get x to have the value of z, modify it, and use the modified
> value, without z being modified overall? Thanks, guys ;)
In general, something like:
def test(x):
import copy
x=copy.copy(x)
# or x=copy.deepcopy() (to taste)
x.append( ... )
just for lists:
def test(x):
x=x[:]
x.append(3)
The latter is fairly idiomatic; I've never used the former (I don't
think).
Cheers,
M.
--
112. Computer Science is embarrassed by the computer.
-- Alan Perlis, http://www.cs.yale.edu/~perlis-alan/quotes.html
More information about the Python-list
mailing list