I want to iterate over a list pair-wise in Python, except the list has an odd number of elements.
I know if this list is even for item1,item2 in zip(alist[0::2],alist[1::2])
would work,
but if the list is odd the loop breaks out before it processes the last item.
Is there any efficient way to handle this?
Example:
list a = (a,b,c,d,e,f,g)
Expected elements in each iteration:
(a,b)
(c,d)
(e,f)
(g,None) # or some other placeother value for the non-existent 2nd element of the pair
CodePudding user response:
You can use itertools.zip_longest
:
from itertools import zip_longest
alist = ["a", "b", "c", "d", "e", "f", "g"]
for i in zip_longest(alist[0::2], alist[1::2]):
print(i)
Prints:
('a', 'b')
('c', 'd')
('e', 'f')
('g', None)
CodePudding user response:
You can append None
:
for item1,item2 in zip(alist[0::2],alist[1::2] [None]):
...