Printing n elements per line in a list

Neil Cerutti horpner at yahoo.com
Thu Aug 17 10:29:56 EDT 2006


On 2006-08-15, unexpected <sumesh.chopra at gmail.com> 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 can't resist putting in my oar: 

def print_per(seq, n, isep=" ", rsep="\n"):
    """Print the items in seq, splitting into records of length n.
    
    Trailing records may be shorter than length n."""
    t = len(seq)
    for i in xrange(n, t+1, n):
        print isep.join(map(str, seq[i-n:i]))+rsep,
    t = t % n
    if t > 0:
        print isep.join(map(str, seq[-t:]))+rsep,

That's probably similar to some of the other mostly
non-functional solutions posted.

-- 
Neil Cerutti



More information about the Python-list mailing list