I can loop through a Python (v.2.6) list without specifying indices, using the following “Pythonic” syntax:
the_list = [2, 3, 5, 7, 11, 13]
for item in the_list:
print item + 2
But if I want to perform an operation on two consecutive indices, I think I then have to specify index numbers, with a corresponding change to the range of the for loop:
the_list = [2, 3, 5, 7, 11, 13]
for i in xrange(len(the_list)-1):
print the_list[i] + the_list[i+1]
Is that correct? Or is there a way to remain Pythonic and avoid using the expression xrange(len(the_list)-1)?
I’m fond of the
pairwiserecipe as listed in the docs to theitertoolsmodule:Then…
You can also just
zipthe list with a slice of itself: