Reputation: 29445
Is there a way to read two items at a time in a for loop in python? If yes, what is the best way?
For example:
a = [1,2,3,4,5,6,7,8,9]
for ix, i in enumerate(a):
j = a[ix+1]
print("i:", i, "j:", j)
But it will fail when i
reaches the last item because a[ix+1]
doesn't exist. Is there a better way which will never fail?
Upvotes: 0
Views: 557
Reputation: 82765
You can use itertools.zip_longest
Ex:
from itertools import zip_longest
a = [1,2,3,4,5,6,7,8,9]
for i,v in zip_longest(a, a[1:]):
print(i, v)
Output:
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 None
Upvotes: 1
Reputation: 18367
If you want to use the for loop, you should iterate until the -1 value:
for i in (a[:-1]):
j = a[i+1]
print("i:",i,"j:",j)
Upvotes: 1
Reputation: 16583
You can fix your code by slicing out the last item:
a = [1,2,3,4,5,6,7,8,9]
for ix, i in enumerate(a[:-1]):
j = a[ix+1]
print("i:", i, "j:", j)
A better way is to use zip
:
a = [1,2,3,4,5,6,7,8,9]
for i, j in zip(a, a[1:]):
print("i:", i, "j:", j)
Upvotes: 1