[Solved] Get Pairs of List Python [duplicate]


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, new
        old = new

Or you can get fancier deploying the powerful itertools instead, as in the pairwise recipe proposed by @HughBothwell .

1

solved Get Pairs of List Python [duplicate]