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.
Enumerate returns a tuple with the index number and the value. I print the value and the following element of the list
ex_list[i+1]
. The ifi < len(list) - 1
means if v is not the last member of the list. If it is: print v and the first element of the listprint v, ex_list[0]
.Edit:
You can make it return a list. Just append the printed tuples to a list and return it.
Here's a version that supports an optional start index (for example to return (4, 0) as the first pair, use start = -1:
Of course, you can always use a deque:
I've coded myself the tuple general versions, I like the first one for it's ellegant simplicity, the more I look at it, the more Pythonic it feels to me... after all, what is more Pythonic than a one liner with zip, asterisk argument expansion, list comprehensions, list slicing, list concatenation and "range"?
The itertools version should be efficient enough even for large lists...
And a version for non-indexable sequences:
Anyway, thanks everybody for your suggestions! :-)
To answer your question about solving for the general case:
The output is like this:
Even shorter version of Fortran's zip * range solution (with lambda this time;):
gives: