Passing by value instead of reference
Quinn Dunkan
quinn at riyal.ugcs.caltech.edu
Sat May 13 11:07:51 EDT 2000
On Wed, 10 May 2000 13:33:52 -0600, Jeff Massung <jmassung at magpiesystems.com>
wrote:
>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 ;)
Make a copy:
def test(x):
x_copy = x[:]
x_copy.append(3)
print x_copy
z = [1, 2]
test(z)
Although usually I'd write a function to operate on its args in place, and the
caller can pass a copy if that's what he wants. Actualy, usually I write a
method which naturally operates on its self in-place :) Also see the `copy'
module for deep copies.
More information about the Python-list
mailing list