How to initialise a 2D array in Python?

Oceanescence picture Oceanescence · Jun 3, 2014 · Viewed 46k times · Source

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).

Answer

arshajii picture arshajii · Jun 3, 2014

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