istep() addition to itertool? (Was: Re: Printing n elements per line in a list)

Rhamphoryncus rhamph at gmail.com
Sat Aug 19 19:12:51 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.

I've run into this problem a few times, and although many solutions
have been presented specifically for printing I would like to present a
more general alternative.

from itertools import chain
def istepline(step, iterator):
    i = 0
    while i < step:
        yield iterator.next()
        i += 1

def istep(iterable, step):
    iterator = iter(iterable)  # Make sure we won't restart iteration
    while True:
        # We rely on istepline()'s side-effect of progressing the
        # iterator.
        start = iterator.next()
        rest = istepline(step - 1, iterator)
        yield chain((start,), rest)
        for i in rest:
            pass  # Exhaust rest to make sure the iterator has
                  # progressed properly.

>>> i = istep(range(12), 5)
>>> for x in i: print list(x)
...
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[10, 11]

>>> i = istep(range(12), 5)
>>> for x in i: print x
...
<itertools.chain object at 0xa7d3268c>
<itertools.chain object at 0xa7d3260c>
<itertools.chain object at 0xa7d3266c>

>>> from itertools import islice, chain, repeat
>>> def pad(iterable, n, pad): return islice(chain(iterable, repeat(pad)), n)
>>> i = istep(range(12), 5)
>>> for x in i: print list(pad(x, 5, None))
...
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[10, 11, None, None, None]

Would anybody else find this useful?  Maybe worth adding it to itertool?




More information about the Python-list mailing list