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.
lst[0]
tolst[:1]
to make it work for an empty sequence. The code becomes more symmetrical, too. β Halsy+[lst[:1]]
should be replaced by+lst[:1]
, isn't it ? β Wiskind[lst[0]]
when I wrote it, I don't know why @colonelpanic changed it π€· β Casabonne