Print lists in a list in columns

Question:

I have a list with lists and I want to print it in columns w/o any additional modules to import (i.e. pprint). The task is only for me to understand iteration over lists. This is my list of lists:

tableData = [['a', 'b', 'c', 'd'],
            ['1', '2', '3', '4'],
            ['one', 'two', 'three', 'four']]

And I want it to look like this:

a    1    one
b    2    two
c    3    three
d    4    four

I managed to somewhat hard-code the first line of it but I can’t figure out how to model the iteration. See:

def printTable(table):
    print(table[0][0].rjust(4," ") + table[1][0].rjust(4," ") + table[2][0].rjust(4," "))
Asked By: Jean Zombie

||

Answers:

You want to transpose this. This is most easy in python. After that, you just need to care about your own printing format.

transposed_tabe = zip(*tableData )

if you have a list as my_list = [(‘Math’, 80), (‘Physics’,90), (‘Biology’, 50)] then we can say this is 3X2 matrix. The transpose of it will 2X3 matrix.

transposed_tabe = zip(*my_list )

will make following output

[(‘Math’, ‘Physics’, ‘Biology’), (80, 90, 50)]

Answered By: Saiful Azad

You can use zip() like so:

>>> for v in zip(*tableData):
        print (*v)

a 1 one
b 2 two
c 3 three
d 4 four

You can obviously improve the formatting (like @Holt did very well) but this is the basic way 🙂

Answered By: Idos

You can use zip to transpose your table and then use a formatted string to output your rows:

row_format = '{:<4}' * len(tableData)
for t in zip(*tableData):
    print(row_format.format(*t))
Answered By: Holt

If you still want mutable strings, simply print one row at a time:

for k in range(len(tableData[0])):
    for v in range(len(tableData)):
        print(tableData[v][k], end = ' ')
    print()

In this way you can use classic string methods ljust() rjust() and center() to format your columns.

Answered By: SampleMe

If you want to automate use of .rjust, assuming you have lists with same number of strings, you can do it like this:

def printTable(data):
    colWidths = [0] * len(data)
    for i in range(len(data)):
        colWidths[i] = len(max(data[i], key=len))

    for item in range(len(data[0])):
        for i in range(len(data)):
            print(str(data[i][item]).rjust(colWidths[i]), end=' ')
        print()


printTable(tableData)

This way you don’t have to manually check the length of the longest string in list.
Result:

a 1   one 
b 2   two 
c 3 three 
d 4  four 
Answered By: DeTom

Easy to use ‘join’:

print( "n".join( info.keys() ) )
Answered By: Luss Sh