Preferred method for "Assignment by value"

Matimus mccredie at gmail.com
Tue Apr 15 13:46:03 EDT 2008


On Apr 15, 10:23 am, hall.j... at gmail.com wrote:
> 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.


I think you understand the concept, basically you want to make a copy.

Ether of these are acceptable:
x = test[0][:]
OR
x = list(test[0])

this will also work:

import copy
x = copy(test[0])

Matt



More information about the Python-list mailing list