简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM