The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).
I've thought about two unpythonic ways of doing it:
def pairs(lst):
n = len(lst)
for i in range(n):
yield lst[i],lst[(i+1)%n]
and:
def pairs(lst):
return zip(lst,lst[1:]+[lst[:1]])
expected output:
>>> for i in pairs(range(10)):
print i
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
(6, 7)
(7, 8)
(8, 9)
(9, 0)
>>>
any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?
also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.
This infinitely cycles, for good or ill, but is algorithmically very clear.
gives:
more pythonic than this is impossible
replace range(10) with the list you want.
In general "circular indexing" is quite easy in python; just use:
I, as always, like tee:
This might be satisfactory:
If you like this kind of stuff, look at python articles on wordaligned.org. The author has a special love of generators in python.
Works on any non-empty sequence, no indexing required.