To create a two-dimensional array in Python:
aList = [[0] * cols for i inrange(rows)]
If we wanted to create a 2D array in Python, how would we write it?
>>> A = [0]* 3 * 4
>>> B = [[0]*3] * 4
Is it A or B? Of course it's B! Or take a look at the output first:
>>> A
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> B
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
Unsurprisingly, we should B = [[0]*3]*4
create a 2D array as follows.
! ! ! ! ! ! ! ! BUT ! ! ! ! ! ! ! ! !
When you create a two-dimensional array in the above way, if you change a number in the two-dimensional array, what will the output be? Let's try it. For example, we change the second number in the first line to 2, B[0][1] = 2
, and output:
>>> B
[[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]]
Why it came out like this? ! !
Because list is a variable type in Python, dear! Creating a two-dimensional array as follows B = [[0]*3]*4
is just 4 references to the elements of this empty list, and modifying any one element will change the entire list.
Another chestnut:
>>> A = [0]*3
>>> B = A
>>> B[0] = 1
>>> A
[1, 0, 0]
Pit father! !
So, to create a two-dimensional array in Python you should write:
>>> C = [[0]*3 for i in range(4)]
>>> C
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> C[0][1] = 2
>>> C
[[0, 2, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
So next time you create a 2D array in Python remember this:
aList = [[0] * cols for i in range(rows)]
#output the number of rows and columns of the array print x.shape # (4, 3) #only output the number of rows print x.shape[0] # 4 #only output the number of columns print x.shape [1] # 3