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

0

5 Answers 5

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]]
Sign up to request clarification or add additional context in comments.

3 Comments

I can do this using this as well: nums = [[0]*4]*4 and it works fine. Is it right method?
@MehulMohan No, because each sublist will really be the same object. Try doing nums[0][0] = 1 and see what nums becomes.
Woah @arshaji can you give a detailed reason why did that happen?
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]]

1 Comment

Could you explain your answer?
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)

Comments

0

numpy has something for this:

numpy.zeros((3,3))

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.