Iterate every 2 elements from list at a time
One solution is
for v, w in zip(l[::2],l[1::2]):
print [v, w]
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
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]
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