Search code examples
pythonpython-3.xlistlist-comprehension

I'm trying list comprehensions for printing 0's and 1's but it gives an error


So basically I'm trying to print an 8x8 grid witch has 0's and 1's like this:

1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

I need it in a nested loop. And I'm using this code but it Isn't working:

def print_board(board):
    board = [1 for i in range(8)] + board[3:]
    board = board[::-1] #reverse
    board = [1 for i in range(8)] + board[3:]
    for i in range(len(board)):
        print(board[i])
        print(" ".join([str(x) for x in board[i]]))
board=[]
for i in range(8):
        board.append([0] * 8)
print_board(board)

the error is:

001 | 1
002 | Traceback (most recent call last):
003 |   File "<string>", line 11, in <module>
004 |   File "<string>", line 7, in print_board
005 | TypeError: 'int' object is not iterable

Using latest version (3.10) of python


Solution

  • Not sure if this is really what you're looking for but:

    a = []
    
    for i in range(8):
        match i:
            case 3 | 4:
                r = [0] * 8
            case _:
                r = [1] * 8
        a.append(r)
    
    for r in a:
        print(*r)
    

    Output:

    1 1 1 1 1 1 1 1
    1 1 1 1 1 1 1 1
    1 1 1 1 1 1 1 1
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    1 1 1 1 1 1 1 1
    1 1 1 1 1 1 1 1
    1 1 1 1 1 1 1 1