c = [1,2,3,4,5,6,7,8,9,10]for a,b in func(c):doSomething()
So func() have to return (1,2) (2,3) (3,4) ... (8,9) (9,10)
Is there a elegant method in python 2.7 to achieve this?
c = [1,2,3,4,5,6,7,8,9,10]for a,b in func(c):doSomething()
So func() have to return (1,2) (2,3) (3,4) ... (8,9) (9,10)
Is there a elegant method in python 2.7 to achieve this?
Sure, there are many ways. Simplest:
def func(alist):return zip(alist, alist[1:])
This spends a lot of memory in Python 2, since zip
makes an actual list and so does the slicing. There are several alternatives focused on generators that offer memory savings, such as a very simple:
def func(alist):it = iter(alist)old = next(it, None)for new in it:yield old, newold = new
Or you can get fancier deploying the powerful itertools
instead, as in the pairwise
recipe proposed by @HughBothwell .