6

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

Oceanescence
  • 1,967
  • 3
  • 18
  • 28

5 Answers5

18

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]]
arshajii
  • 127,459
  • 24
  • 238
  • 287
4
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]]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

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)
Chris Mukherjee
  • 841
  • 9
  • 25
0

numpy has something for this:

numpy.zeros((3,3))
Ben
  • 2,065
  • 1
  • 13
  • 19
0

You can use the style of pseudocode given or simply just use a python one liner

chess_board = [[x]*3 for _ in range(y)] --> list comprehension

or you can use the plain loop style of other languages like java. I prefer the one liner as it looks much nicer and cleaner.