What is the difference between the below two ways for creating 2d array in python?
def arrays(row, column):
myList = [[None]*column for i in range(row)]
def arrays(row, column):
myList = [[None]*column]*row
What is the difference between the below two ways for creating 2d array in python?
def arrays(row, column):
myList = [[None]*column for i in range(row)]
def arrays(row, column):
myList = [[None]*column]*row
In the first case, separate pointers are used to store your sublists.
In the second instance, the same pointer is used. So changing the value of one will also change the others.
Here's an illustrative example:-
def arrays1(row, column):
return [[None]*column for i in range(row)]
def arrays2(row, column):
return [[None]*column]*row
x = arrays1(2, 2)
y = arrays2(2, 2)
x[0][0] = 1
y[0][0] = 1
print(x) # [[1, None], [None, None]]
print(y) # [[1, None], [1, None]]