How do I get each row on a separate line?

Question:

This program prints a table with 5 rows and 3 columns. Each row needs to be on a separate line. Use end=""

table = []

ROWS = 5
COLUMNS = 3
for i in range(ROWS) :
   row = [0] * COLUMNS
   table.append(row)
print(table)
Asked By: toothpaste_123

||

Answers:

By itself, print() can’t put spaces between a list’s elements it just calls an internal function of the list class to ask what it should print. Instead, you can define your own special print function like this:

def printTable(table):
    print('[')
    for el in table:
        print(f'  {el},')
    print(']')


table = []

ROWS = 5
COLUMNS = 3
for i in range(ROWS):
    row = [0] * COLUMNS
    table.append(row)

printTable(table)

You could also pass each element of the array as a separate parameter with a generator expression and use the sep keyword argument:

def printTable(table):
    print('[')
    print(*(f'  {el}' for el in table), sep="n")
    print(']')


table = []

ROWS = 5
COLUMNS = 3
for i in range(ROWS):
    row = [0] * COLUMNS
    table.append(row)

printTable(table)

I also used an f-string to provide a bit of nice indentation, but this is optional.

Answered By: Michael M.

You can use tabulate module.

#IMPORT TABULATE
from tabulate import tabulate

#YOUR CODE
table = []
ROWS = 5
COLUMNS = 3
for i in range(ROWS) :
   row = [0] * COLUMNS
   table.append(row)

#PRINT
print(tabulate(table))
Answered By: Pavan Chandaka
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.