# [Tutor] Printing a formatted list (of lists)

Jeff Shannon jeff@ccvcorp.com
Tue, 30 Jul 2002 10:07:46 -0700

```Allyn Weaks wrote:

> On 29/7/02, Jeff Shannon wrote:
>
> >If you *don't* know the number of columns
> ...
> >If you don't know what your maximum column width should be
>
> I expect that this sort of thing comes up often enough that it's worth
> writing up something general that can figure out how many of this and
> that, and all the widths and such itself.  Think once, day dream ad
> lib...

Well, there was a recent thread here about the best way to find the maximum

maxlen = max( map(len, mylist) )

If you're doing this over a list of lists, you'd need to find the max length of
each nested list, and then use the largest of those:

maxlen = max( [ max( map(len, innerlist) for innerlist in outerlist ] )

Just in case that's a bit too much happening at once to be easy to follow ;)
it's equivalent to the following:

def FindMaxLength(outerlist):
# create a list of all the maximum lengths
lengths = []
# now, for each of the nested lists...
for innerlist in outerlist:
# calculate the max length and add it to lengths list
lengths.append( max(map(len, mylist) ) )
# then find the largest of them
maxlen = max( lengths)
return maxlen

(Personally, I'd prefer to use the one-liner, but I'd probably wrap it up in a
function anyhow.)

If you want to go whole-hog and do something *really* fancy, you could write a
routine that would find maximum lengths for each column independently (perhaps
returning a list of column lengths), then another routine that would convert that
list of column lengths into a suitable formatstring and use the previously
discussed string substitution methods to print out your table.  (I have some
thoughts on how to approach this, too, but won't work out details unless you
really want it. ;) )

Jeff Shannon
Technician/Programmer
Credit International

```