Printing Columns

Peter Hansen peter at
Tue Apr 15 20:32:21 CEST 2003

Lindstrom Greg - glinds wrote:
> myList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
> [...]
> but I would like
>         A       D       G
>         B       E       H
>         C       F
> problem is, the code (all 12 lines) is a bit convoluted and would not be
> easy for the next person using it to figure out (and in my mind,
> maintainability is priority one; that's why I use Python).  I would like to
> know if there is a "pythonic" way to do this. So, here are the specs....
> Given a list of length N with 0<=N<=infinity and a number of columns, C (C>0
> and may be less than N), how do we print out the elements of the list in the
> above (column major?) form?

Unmaintainable, but with the "virtue" of being shorter than 12 lines:  ;-)

c = 3
print '\n'.join([' '.join([myList[i] for i in range(s, len(myList), c)]) 
    for s in range(len(myList)/c+1)])

A  D  G
B  E  H
C  F

Note: relies on current integer division, otherwise you need to add an
int() call in the last bit.

Disclaimer: may not work with *all* values across the range specified for N...

(I'm not in any way suggesting the above is maintainable, but on the other
hand it's a compact way of showing you want I would do: use a list 
comprehension which chooses a subset of the items using the step parameter 
on range(), and iterating over the starting offset for that list.)

(I'd also write tests first, to drive the code and make sure it actually
works in all cases.  The above might not.)


More information about the Python-list mailing list