Iterate through list two items at a time

Gerard Flanagan grflanagan at yahoo.co.uk
Wed Jan 3 01:32:36 EST 2007


Dave Dean wrote:

> Hi all,
>   I'm looking for a way to iterate through a list, two (or more) items at a
> time.  Basically...
>
>   myList = [1,2,3,4,5,6]
>
> I'd like to be able to pull out two items at a time - simple examples would
> be:
> Create this output:
> 1 2
> 3 4
> 5 6
>
> Create this list:
> [(1,2), (3,4), (5,6)]
>

A "padding generator" version:

def chunk( seq, size, pad=None ):
    '''
    Slice a list into consecutive disjoint 'chunks' of
    length equal to size. The last chunk is padded if necessary.

    >>> list(chunk(range(1,10),3))
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    >>> list(chunk(range(1,9),3))
    [[1, 2, 3], [4, 5, 6], [7, 8, None]]
    >>> list(chunk(range(1,8),3))
    [[1, 2, 3], [4, 5, 6], [7, None, None]]
    >>> list(chunk(range(1,10),1))
    [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
    >>> list(chunk(range(1,10),9))
    [[1, 2, 3, 4, 5, 6, 7, 8, 9]]
    >>> for X in chunk([],3): print X
    >>>
    '''
    n = len(seq)
    mod = n % size
    for i in xrange(0, n-mod, size):
        yield seq[i:i+size]
    if mod:
        padding = [pad] * (size-mod)
        yield seq[-mod:] + padding

------------------------------------------------------------------

Gerard




More information about the Python-list mailing list