Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a copy of a 2D array in Python? [duplicate]

X is a 2D array. I want to have a new variable Y that which has the same value as the array X. Moreover, any further manipulations with Y should not influence the value of the X.

It seems to me so natural to use y = x. But it does not work with arrays. If I do it this way and then changes y, the x will be changed too. I found out that the problem can be solved like that: y = x[:]

But it does not work with 2D array. For example:

x = [[1,2],[3,4]] y = x[:] y[0][0]= 1000 print x 

returns [ [1000, 2], [3, 4] ]. It also does not help if I replace y=x[:] by y = x[:][:].

Does anybody know what is a proper and simple way to do it?

like image 452
Roman Avatar asked Jun 30 '11 09:06

Roman


People also ask

How do you duplicate an array in Python?

To create a deep copy of an array in Python, use the array. copy() method. The array. copy() method does not take any argument because it is called on the original array and returns the deep copied array.

How do you clone a 2D array?

Using clone() method A simple solution is to use the clone() method to clone a 2-dimensional array in Java. The following solution uses a for loop to iterate over each row of the original array and then calls the clone() method to copy each row.

How do I copy one 2D array to another?

Copying Arrays Using arraycopy() method src - source array you want to copy. srcPos - starting position (index) in the source array. dest - destination array where elements will be copied from the source. destPos - starting position (index) in the destination array.

How do you copy an array of a matrix in Python?

With the help of Numpy matrix. copy() method, we can make a copy of all the data elements that is present in matrix. If we change any data element in the copy, it will not affect the original matrix.


1 Answers

Using deepcopy() or copy() is a good solution. For a simple 2D-array case

y = [row[:] for row in x] 
like image 75
Ryan Ye Avatar answered Oct 11 '22 10:10

Ryan Ye