[Tutor] Printing a formatted list (of lists)

Jeff Shannon jeff@ccvcorp.com
Mon, 29 Jul 2002 10:28:45 -0700


Allyn Weaks wrote:

> Python 2.n on unix.
>
> I have a table that's a list of lists (values can be mixed
> numbers/text).  Is there a clean way to print a formatted list?  What I
> have works, but it seems that there ought to be a more list-oriented
> way of formatting the list part.  Or is this one of those places where
> one accepts the explicit loop?  I've tried out list comprehension
> variations 'til I'm dizzy with nothing but assorted errors.
>
> for j in range(len(table)):
>     print `table[j]`.rjust(columnwidth),

Well, the above snippet can be simplified as

for cell in table:
    print cell.rjust(columnwidth),

but that's not much of an improvement.  (I also don't think it does what you
want, really, anyhow, but my code will do the same thing as yours.)

If you know the number (and width) of columns in your table, then you can do
something like this:

for line in table:
    print "%15s %15s %15s %15s" % tuple(line)

This has the advantage that you can adjust the size of each column, if you
want -- the first column can be half as wide as the second, simply by
modifying the format numbers.

If you *don't* know the number of columns, but have a good idea what width
you want to use, then you can maybe use a list comprehension to create
column-width strings, then join those together and print the result:

for line in table:
    columns = ["%15s" % cell for cell in line]
    print ' '.join(columns)

If you don't know what your maximum column width should be, then you'll have
to iterate through the entire list of lists to determine what the longest
item is.  Using that length, you can then generate a format string for the
above snippet (the "%15s" is the format string, you'd need to assemble one
with '15' replaced by whatever the maximum width should be).

Hope this at least gives you some ideas...

Jeff Shannon
Technician/Programmer
Credit International