[Tutor] print as columns

Christopher Smith csmith@blakeschool.org
Sun, 15 Jul 2001 15:15:12 -0500


(Mike Serpa <onav@yahoo.com> wrote about printListColumns.)

I have a couple suggestions regarding your printListColumns:

1) you can find the longest in a list of lists by using the
reduce function which keeps applying the function to 
successive pairs of elements from a list:

n=len(reduce(lambda a,b:max(a,b),l))
  ---        ------------------- -
   ^            ^                ^->the list of lists (called Lists in
your program)
   |            |
   |            |_ the function which returns the longer of two lists
   |
   |_ when the reduce is done we will know the longest list, len gives the
length of it

Example:

a=[1,2,3,4]
b=[5,6,7]
c=[8,9,10,11,12]

n=len( reduce( lambda a,b:max(a,b), [a,b,c] ))

n is 5

2) Instead of padding, you might consider using the try/except 
construction to not print the list elements that don't 
exist.  Here's how it looks for a list of 3 elements which is to be
printed in 5 rows.

	for j in range(5):
		try:
			print str(l[j].ljust(20),  #if l[j] exists, print it
		except:
			print ''.ljust(20)  #otherwise format a null string

Thanks for the thought provoking post.

/c