Say I want to iterate through a list. Each time I iterate I want to compute something using both the current and next terms. I could do something like
mylist = [1, 2, 3, 4]
for i in range(len(mylist)):
try:
compute(mylist[i], mylist[i+1])
except IndexError:
compute(mylist[i])
I could also do
mylist = [1, 2, 3, 4]
for num in mylist:
try:
compute(num, mylist[mylist.index(num)+1])
except IndexError:
compute(num)
Neither of these seems particularly good. Is there a more pythonic approach to doing this?