Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a shallow copy of a list in Python

I am trying to implement an algorithm in Python to generate all Permutations of a list. But I In my for loop I wish to keep the original prefix and rest lists intact, and therefore I am trying to make a copy of those lists using newprefix and newrest, however on printing the variable rest at each iteration, I see that even the variable rest is getting modified! How can I make a shallow copy of the list in Python? Or is there another issue with my attempted 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']) 
like image 932
KT100 Avatar asked Apr 29 '13 02:04

KT100


People also ask

How do you shallow copy a list in Python?

import copy a = [somestuff] b = copy. copy(a) # Shallow copy here. c = copy. deepcopy(a) # Deep copy here.

Does list () create a shallow copy?

In the official Python documentation said that list. copy() returns a shallow copy of the list. But according to the following code it is deep copy since the change of one list does not lead to the change in another.

Does Python have shallow copy?

In Python, a shallow copy is a “one-level-deep” copy. The copied object contains references to the child objects of the original object. A deep copy is completely independent of the original object. It constructs a new collection object by recursively populating it with copies of the child objects.


2 Answers

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

newprefix = prefix[:] 

Or pass it into the list constructor:

newprefix = list(prefix) 

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

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']) 
like image 113
Blender Avatar answered Sep 18 '22 04:09

Blender


import copy  a = [somestuff] b = copy.copy(a) # Shallow copy here. c = copy.deepcopy(a) # Deep copy here. 

The copy module is worth knowing about. https://docs.python.org/3/library/copy.html

(Python 2) http://docs.python.org/2/library/copy.html

like image 22
BlackVegetable Avatar answered Sep 17 '22 04:09

BlackVegetable