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

Roman picture Roman · Jun 30, 2011 · Viewed 81.3k times · Source

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?

Answer

Ryan Ye picture Ryan Ye · Jun 30, 2011

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

y = [row[:] for row in x]