I have an double array
alist[1][1]=-1
alist2=[]
for x in xrange(10):
alist2.append(alist[x])
alist2[1][1]=15
print alist[1][1]
and I get 15. Clearly I'm passing a pointer rather than an actual variable... Is there an easy way to make a seperate double array (no shared pointers) without having to do a double for loop?
Thanks, Dan
ALGORITHM: STEP 1: Declare and initialize an array. STEP 2: Declare another array of the same size as of the first one. STEP 3: Loop through the first array from 0 to length of the array and copy an element from the first array to the second array that is arr1[i] = arr2[i].
To make a deep copy, use the deepcopy() function of the copy module. In a deep copy, copies are inserted instead of references to objects, so changing one does not change the other.
The Python copy() method creates a copy of an existing list. The copy() method is added to the end of a list object and so it does not accept any parameters. copy() returns a new list. Python includes a built-in function to support creating a shallow copy of a list: copy() .
I think copy.deepcopy() is for just this case.
You can use somelist[:]
, that is a slice like somelist[1:2]
from beginning to end, to create a (shallow) copy of a list. Applying this to your for-loop gives:
alist2 = []
for x in xrange(10):
alist2.append(alist[x][:])
This can also be written as a list comprehension:
alist2 = [item[:] for item in alist]
A list of lists is not usually a great solution for making a 2d array. You probably want to use numpy, which provides a very useful, efficient n-dimensional array type. numpy arrays can be copied.
Other solutions that are usually better than a plain list of lists include a dict with tuples as keys (d[1, 1]
would be the 1, 1 component) or defining your own 2d array class. Of course, dicts can be copied and you could abstract copying away for your class.
To copy a list of lists, you can use copy.deepcopy
, which will go one level deep when copying.
If you're already looping over the list anyway then just copying the inner lists as you go is easiest, as per seanmonstar's answer.
If you just want to do a deep copy of the list you could call copy.deepcopy()
on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With