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?
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.
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.
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.
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.
Using deepcopy() or copy() is a good solution. For a simple 2D-array case
y = [row[:] for row in x]
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