How to make a shallow copy of a list in Python

I am trying to implement an algorithm in Python to create all permutations of a list. But in my for loop, I want to keep the original prefix and the lists of remains intact, and so I try to make a copy of these lists with newprefix and newrest, however when I print the variable at each iteration, I see that even the variable rest changes! How to make a shallow copy of a list in Python? Or is there another problem with my attempt at logic?

def perm(prefix, rest): if len(rest) == 0: print prefix for i in range(len(rest)): #prints in the for loop are just for debugging print "rest:", rest print "i=", i newprefix = prefix newprefix.append(rest[i]) newrest = rest newrest.pop(i) print "old pre : ", prefix print "newpre=", newprefix print "newrest=", newrest perm(newprefix, newrest) perm([], ['a','b','c']) 
+11
python
Apr 29 '13 at 2:25
source share
2 answers

To make a shallow copy, you can slice the list:

 newprefix = prefix[:] 

Or pass it to the list constructor:

 newprefix = list(prefix) 

Also, I think you can simplify your code a bit:

 def perm(prefix, rest): print prefix, rest for i in range(len(rest)): perm(prefix + [rest[i]], rest[:i] + rest[i + 1:]) perm([], ['a','b','c']) 
+27
Apr 29 '13 at 2:26
source share
 import copy a = [somestuff] b = copy.copy(a) # Shallow copy here. c = copy.deepcopy(a) # Deep copy here. 

Copy module is worth knowing. http://docs.python.org/2/library/copy.html

+6
Apr 29 '13 at 2:27
source share



All Articles