Printing n elements per line in a list

Dan Sommers me at privacy.net
Tue Aug 15 20:41:45 EDT 2006


On 15 Aug 2006 16:51:29 -0700,
"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

Perhaps not the prettiest, but I can't think of anything simpler to read
six months from now:

    counter = 0
    for an_element in the_list:
        print an_element,
        counter = counter + 1
        if counter == n:
            print
            counter = 0

Regards,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>
"I wish people would die in alphabetical order." -- My wife, the genealogist



More information about the Python-list mailing list