Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise a 2D array in Python?

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

like image 227
Oceanescence Avatar asked Jun 03 '14 19:06

Oceanescence


1 Answers

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]]
like image 66
arshajii Avatar answered Nov 03 '22 01:11

arshajii