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]
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]
One solution is
for v, w in zip(l[::2],l[1::2]):
print [v, w]
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With