shallow copy's

Erik Max Francis max at alcyone.com
Fri Jul 5 15:34:45 EDT 2002


Rajarshi Guha wrote:

>   I have some code:
> 
> a = [1,2,3,4]
> b = a
> 
> Do some operations on a
> Will the contents of b mirror a? Or will b remain unchanged?

b will change as well, because a and b are both bound to the same object
(the list).  Note that the Subject of your message reads "shallow
copies," but this is not a copy operation at all, it is merely a
rebinding.  The way to tell if two objects are the same is with the `is'
operator; a is b will evaluate to true if a and b refer to the same
object.  This would be a shallow copy:

	import copy

	a = [1, 2, 3, 4]
	b = copy.copy(a)

or just this:

	a = [1, 2, 3, 4]
	b = a[:]

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ See the son in your bad day / Smell the flowers in the valley
\__/ Chante Moore
    Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/
 A personal guide to Aliens vs. Predator 2.



More information about the Python-list mailing list