Python: duplicate an array

I have a 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. It’s clear that I am passing a pointer, not an actual variable ... Is there an easy way to make a double array separate (without shared pointers) without needing to make a double for the loop ?

Thanks Dan

+4
source share
6 answers

A list of lists is usually not a great solution for creating 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 simple list of lists include dict with tuples as keys ( d[1, 1] will be component 1, 1) or define your own 2d array class. Of course, dicts can be copied, and you can ignore copying for your class.

To copy the list of lists, you can use copy.deepcopy , which when copying will go one level.

+4
source

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

+9
source

You can use somelist[:] , that is, a fragment of type somelist[1:2] from start to finish to create a (shallow) copy of the list. Applying this to your for-loop, you get:

 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] 
+5
source

make a copy of the list when adding.

  alist2.append(alist[x][:]) 
+1
source

If you iterate over the list anyway, just simply copy the internal lists when you go, the easiest way is as seanmonstar's answer.

If you just want to make a deep copy of the list, you can call it copy.deepcopy() .

+1
source

You can usually do something like:

 new_list = old_list[:] 

So, could you throw this in your only for loop?

 for x in range(10): alist2.append(alist[x][:]) 
0
source

Source: https://habr.com/ru/post/1304226/


All Articles