Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Create a duplicate of an array

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

like image 216
Dan Avatar asked Mar 16 '10 05:03

Dan


People also ask

How do you create an array from an existing array in Python?

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].

How do you deep copy an array in Python?

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.

What does Copy () do in Python?

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() .


5 Answers

I think copy.deepcopy() is for just this case.

like image 191
msw Avatar answered Oct 22 '22 06:10

msw


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]
like image 44
sth Avatar answered Oct 22 '22 05:10

sth


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.

like image 35
Mike Graham Avatar answered Oct 22 '22 07:10

Mike Graham


make a copy of the list when append.

  alist2.append(alist[x][:])
like image 43
Dyno Fu Avatar answered Oct 22 '22 07:10

Dyno Fu


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.

like image 1
EMP Avatar answered Oct 22 '22 06:10

EMP