Printing n elements per line in a list

John Machin sjmachin at lexicon.net
Tue Aug 15 21:33:51 EDT 2006


Dan Sommers wrote:

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

Yes, often simple old-fashioned ways are the best. A little verbose,
though. And I'd do some old-fashioned testing -- the above needs "if
counter: print" after the loop has finished, to get the final '\n'  for
cases where there are not an even multiple of n elements.

>>> def wrapn(alist, n):
...     ctr = 0
...     for item in alist:
...         print item,
...         ctr = (ctr + 1) % n
...         if not ctr:
...             print
...     if ctr:
...         print
...
>>> for k in range(8):
...     print '--- %d ---' % k
...     wrapn(range(k), 3)
...
--- 0 ---
--- 1 ---
0
--- 2 ---
0 1
--- 3 ---
0 1 2
--- 4 ---
0 1 2
3
--- 5 ---
0 1 2
3 4
--- 6 ---
0 1 2
3 4 5
--- 7 ---
0 1 2
3 4 5
6
>>>

Cheers,
John




More information about the Python-list mailing list