Preferred method for "Assignment by value"

hall.jeff at gmail.com hall.jeff at gmail.com
Tue Apr 15 13:23:02 EDT 2008


As a relative new comer to Python, I haven't done a heck of a lot of
hacking around with it. I had my first run in with Python's quirky (to
me at least) tendency to assign by reference rather than by value (I'm
coming from a VBA world so that's the terminology I'm using). I was
surprised that these two cases behave so differently

test = [[1],[2]]
x = test[0]
x[0] = 5
test
>>> [[5],[2]]
x = 1
test
>>>[[5],[2]]
x
>>> 1

Now I've done a little reading and I think I understand the problem...
My issue is, "What's the 'best practise' way of assigning just the
value of something to a new name?"

i.e.
test = [[1,2],[3,4]]
I need to do some data manipulation with the first list in the above
list without changing <test>
obviously x = test[0] will not work as any changes i make will alter
the original...
I found that I could do this:
x = [] + test[0]

that gets me a "pure" (i.e. unconnected to test[0] ) list but that
concerned me as a bit kludgy

Thanks for you time and help.



More information about the Python-list mailing list