koda
koda

Reputation: 31

How to print a 2D list so that each list is on a new line with a space, without any "" or []

I'm having trouble printing a list in a visually appealing manor. An example of the list is

[["-", "-", "-", "-"],["-", "-", "-", "-"],["-", "-", "-", "-"]] 

(the characters won't all necessarily be the same), but I need to print it without using any functions except print, range, len, insert, append, pop, and I cannot use any dictionaries or maps, or import any libraries or use any list-comprehensions. I in turn want:

- - - -
- - - - 
- - - - 

I tried:

def print_board(board): 
    for i in board: 
        row = board[i] 
        for r in row: 
            print(*row[r], "\n")

Upvotes: 1

Views: 8343

Answers (3)

Patrick Artner
Patrick Artner

Reputation: 51643

With better named variables this migh lead to better understanding:

def print_board(board): 
    for innerList in board: 
        for elem in innerList: 
            print(elem + " ", end ='') # no \n after print
        print("") # now \n


b = [["-"]*4]*4       
print_board(b)
print(b)

Output:

- - - -  
- - - -  
- - - -  
- - - -  

[['-', '-', '-', '-'], ['-', '-', '-', '-'], ['-', '-', '-', '-'], ['-', '-', '-', '-']]

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 60974

board = [["-", "-", "-", "-"],["-", "-", "-", "-"],["-", "-", "-", "-"]] 

for row in board:
    print(*row)

This is the easiest way, but relies on argument unpacking (that * star before the row). If you can't use that for whatever reason then you can use the keyword arguments to print to achieve the same result

for row in board:
    for cell in row:
        print(cell, end=' ')
    print()

Upvotes: 1

Barmar
Barmar

Reputation: 780899

You're close, but you misunderstand how for i in <list> works. The iteration variable gets the list elements, not their indexes.

Also, row[r] (if r were the index) would be just a single string, not a list, so you don't need to unpack it with *row[r].

There's no need to include "\n" in the print() call, since it ends the output with a newline by default -- you would have to override that with the end="" option to prevent it.

for row in board:
    for col in row:
        print(col, end=" ") # print each element separated by space
    print() # Add newline

Upvotes: 5

Related Questions