Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 572
Nishant Nawarkhede Avatar asked Feb 13 '14 11:02

Nishant Nawarkhede


4 Answers

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]
like image 146
Ashwini Chaudhary Avatar answered Oct 15 '22 08:10

Ashwini Chaudhary


One solution is

for v, w in zip(l[::2],l[1::2]):
    print [v, w]
like image 32
hivert Avatar answered Oct 15 '22 07:10

hivert


You could do it your way, just add a step part to the slice to make both slices skip a number:

for v, w in zip(l[::2],l[1::2]):  # No need to end at -1 because that's the default
    print [v, w]

But I like helper generators:

def pairwise(iterable):
    i = iter(iterable)
    while True:
       yield i.next(), i.next()

for v, w in pairwise(l):
    print v, w
like image 24
RemcoGerlich Avatar answered Oct 15 '22 08:10

RemcoGerlich


What's wrong with:

l = [1, 2, 3, 4, 5, 6, 7, 8]
for j in range(0, len(l), 2):
        print(l[j: j + 2])

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

assuming the lists have even number of elements

like image 41
Mr_and_Mrs_D Avatar answered Oct 15 '22 07:10

Mr_and_Mrs_D