Search code examples
pythonlistpython-2.7

Iterate every 2 elements from list at a time


Having list as ,

l = [1,2,3,4,5,6,7,8,9,0]

How can i iterate every two elements at a time ?

I am trying this ,

for v, w in zip(l[:-1],l[1:]):
    print [v, w]

and getting output is like ,

[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]
[8, 9]
[9, 0]

Expected output is

[1,2]
[3, 4]
[5, 6]
[7, 8]
[9,10]

Solution

  • You can use iter:

    >>> seq = [1,2,3,4,5,6,7,8,9,10]
    >>> it = iter(seq)
    >>> for x in it:
    ...     print (x, next(it))
    ...     
    [1, 2]
    [3, 4]
    [5, 6]
    [7, 8]
    [9, 10]
    

    You can also use the grouper recipe from itertools:

    >>> from itertools import izip_longest
    >>> def grouper(iterable, n, fillvalue=None):
    ...         "Collect data into fixed-length chunks or blocks"
    ...         # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    ...         args = [iter(iterable)] * n
    ...         return izip_longest(fillvalue=fillvalue, *args)
    ... 
    >>> for x, y in grouper(seq, 2):
    ...     print (x, y)
    ...     
    [1, 2]
    [3, 4]
    [5, 6]
    [7, 8]
    [9, 10]