[Tutor] how to *really* copy a list

kevin parks kp8 at mac.com
Fri Apr 28 03:59:18 CEST 2006

I know there is an answer to this somewhere. it is prolly the biggest 
block to all python n00bs, but it hasn't been an issue for me in a 
Suddenly i am getting bit by it and can't for the life of me keep 
straight the
two way of opperating on lists.

In most case you are fine operating on the list in place and altering 
existing list. In some cases you want your code to stop molesting your 
mutables and really honestly sincerly copy the dang thing. In this case 
i am
making a function that does odd smmetry mirroring. But i want my 
orginal list
to remain intact....

 >>> a = [1, 2, 3, 4]
 >>> mirror(a)
[1, 2, 3, 4, 3, 2, 1]
 >>> a
[1, 2, 3, 4, 3, 2, 1]

clearly this is not happening. believe it or not i googled around 
figuring the
answer would be posted someplace... but if it is i haven't found it. 
Every thing
i land on says copy a list by [:] slicing like i have below...

how to i really (not kidding) copy a list? I swear i used to know this, 
but i haven't had
to do it in a long long long time.

# ===================================

dumb code:

def mirror(seq):
	"""odd symmetry mirroring  [1, 2, 3, 4] --> [1, 2, 3, 4, 3, 2, 1]"""
	foo=seq[:-1]				# copy list, excluding last element for odd symetry
	foo.reverse()				# flip it
	return seq

More information about the Tutor mailing list