Printing n elements per line in a list

Matimus mccredie at gmail.com
Wed Aug 16 23:22:15 EDT 2006


John Machin wrote:
> Matimus wrote:
> > unexpected wrote:
> > > If have a list from 1 to 100, what's the easiest, most elegant way to
> > > print them out, so that there are only n elements per line.
> > >
> > > So if n=5, the printed list would look like:
> > >
> > > 1 2 3 4 5
> > > 6 7 8 9 10
> > > 11 12 13 14 15
> > > etc.
> > >
> > > My search through the previous posts yields methods to print all the
> > > values of the list on a single line, but that's not what I want. I feel
> > > like there is an easy, pretty way to do this. I think it's possible to
> > > hack it up using while loops and some ugly slicing, but hopefully I'm
> > > missing something
> >
> > I suppose 'elegance' is in the eye of the beholder. I agree with the
> > previous posts, a readable for loop is probably the best way to go.
> > I've instead chosen to use the functional paradigm. I thought someone
> > might appreciate this:
> >
> > p = sys.stdout.write
> > map(p,[str(i)+("\n"+" "*(n-1))[i%n] for i in range(1,101)])
>
> At least three strikes:
>
> 1. The functional paradigm AFAIK abjures side effects.
>
> |>>> n = 3
> |>>> map(p,[str(i)+("\n"+" "*(n-1))[i%n] for i in range(1,11)])
> 1 2 3
> 4 5 6
> 7 8 9
> 10 [None, None, None, None, None, None, None, None, None, None]
>
> If you want functional, instead of
>     map(sys.stdout.write, strings)
> do this:
>     sys.stdout.write(''.join(strings))
>
> 2.  This little gem
>     ("\n"+" "*(n-1))[i%n]
> is better written
>     " \n"[i%n==0]
>
> 3. Like some other attempts, it's missing the trailing \n when len(seq)
> % n != 0
>
> 4. It needs elaboration so that it works with any sequence, not just
> range(1, size+1)
>
> Yer out!
>
> Cheers,
> John

Well, I have another at bat, so I will try to redeem myself... using
recursion:

def printTable(l,c):
    print(("%d "*len(l[:c]))%tuple(l[:c]))
    if( len(l[:c]) > 0 ):
        printTable(l[c:],c)

printTable(range(1,101),5)




More information about the Python-list mailing list