Print lists in a list in columns

14,450

Solution 1

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

Solution 2

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))
Share:
14,450

Related videos on Youtube

Jean Zombie
Author by

Jean Zombie

Peace

Updated on July 06, 2022

Comments

  • Jean Zombie
    Jean Zombie almost 2 years

    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," "))