Printing n elements per line in a list

Simon Forman rogue_pedro at yahoo.com
Tue Aug 15 21:21:55 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

>From http://docs.python.org/lib/itertools-recipes.html there's the
grouper() function:

from itertools import izip, chain, repeat

def grouper(n, iterable, padvalue=None):
    """
    Return n-tuples from iterable, padding with padvalue.
    Example:
    grouper(3, 'abcdefg', 'x') -->
    ('a','b','c'), ('d','e','f'), ('g','x','x')
    """
    return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)

R = range(1, 101)

for N in grouper(5, R, ''):
    print ' '.join(str(n) for n in N)

If your iterable is not a multiple of n (of course not the case for 100
and 5), and you don't want the extra spaces at the end of your last
line, you could join the lines with '\n' and stick a call to rstrip()
in there:

G = grouper(5, R, '')
print '\n'.join(' '.join(str(n) for n in N) for N in G).rstrip()

but then you're back to ugly. lol.

Peace,
~Simon




More information about the Python-list mailing list