How to initialise a 2D array in Python?
51,942
Solution 1
If you really want to use for
-loops:
>>> board = []
>>> for i in range(3):
... board.append([])
... for j in range(3):
... board[i].append(0)
...
>>> board
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
But Python makes this easier for you:
>>> board = [[0]*3 for _ in range(3)]
>>> board
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Solution 2
arr=[[0,0,0] for i in range(3)] # create a list with 3 sublists containing [0,0,0]
arr
Out[1]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
If you want an list with 5 sublists containing 4 0's:
In [29]: arr=[[0,0,0,0] for i in range(5)]
In [30]: arr
Out[30]:
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
The range specifies how many sublists you want, ranges start at 0, so ranges 4 is 0,1,2,3,4
.
gives you five [0,0,0,0]
Using the list comprehension is the same as:
arr=[]
for i in range(5):
arr.append([0,0,0,0])
arr
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
Solution 3
If you want something closer to your pseudocode:
board = []
for i in range(3):
board.append([])
for j in range(3):
board[i].append(0)
Author by
Oceanescence
Updated on July 05, 2022Comments
-
Oceanescence almost 2 years
I've been given the pseudo-code:
for i= 1 to 3 for j = 1 to 3 board [i] [j] = 0 next j next i
How would I create this in python?
(The idea is to create a 3 by 3 array with all of the elements set to 0 using a for loop).
-
bjb568 almost 10 yearsCould you explain your answer?
-
mehulmpt about 9 yearsI can do this using this as well:
nums = [[0]*4]*4
and it works fine. Is it right method? -
arshajii about 9 years@MehulMohan No, because each sublist will really be the same object. Try doing
nums[0][0] = 1
and see whatnums
becomes. -
mehulmpt about 9 yearsWoah @arshaji can you give a detailed reason why did that happen?