Printing n elements per line in a list

Gerard Flanagan grflanagan at yahoo.co.uk
Wed Aug 16 04:32:32 EDT 2006


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

just variations on previous answers:

rng = range(1,101)

#ad hoc
for line in ( rng[i:i+5] for i in xrange(0,100,5) ):
    print ' '.join(map(str,line))

#in general
def lines( seq, count=1 ):
    n = len(seq)
    for x in ( seq[i:i+count] for i in xrange(0,n,count) ):
        yield x

for line in lines( rng, 5 ):
    print ' '.join(map(str,line))

Gerard




More information about the Python-list mailing list