Preferred method for "Assignment by value"

Gary Herron gherron at islandtraining.com
Tue Apr 15 19:44:19 CEST 2008


hall.jeff 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.
>   

If you want a *copy* of an object (or portion thereof), you must 
explicitly *specify* a copy.  THere are different ways of doing that 
depending on the object in question.

Lists (and slices thereof) can be copied to a new list withthe slice syntax:
  L[1:4] will copy a limited portion, and
  L[:] will copy the whole list. 
  The kind of copy is only one level deep -- the contents of the copy 
will be references to the contents of L

Dictionaries  have a copy method that creates a new dictionary.
  Again this copy is only one level deep.

The copy modules provides a more general way to copy objects.  It 
provides the ability to produce both shallow and deep copies.

A small note:  In a dozen years of programming in Python, I've used 
these various copy methods perhaps a dozen times or less.   If you find 
you are copying structures often, you are probably not using Python as 
effectively as you could.

Gary Herron





More information about the Python-list mailing list