Anil Yadav
Anil Yadav

Reputation: 75

Two ways to create 2D array in python

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

Upvotes: 4

Views: 253

Answers (1)

jpp
jpp

Reputation: 164623

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]]

Upvotes: 3

Related Questions