Python 3.8: Iterate over 1st and 2nd element, then 2nd and 3rd and so on

Issue

I want to compare certain numbers I have in a list with values from another list by creating a range.
Like this:

r = np.arange(0, 20, 2)

Now, r is an array that looks like this:

array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])

Now, I would like to use a for loop starting with the first two elements of r, and create a range, such that for the first iteration the 1st and 2nd elements are considered, then for the second iteration, the 2nd and 3rd elements are considered.

So it looks like this for each iteration:

range(0,2)
range(2,4)
range(4,6)
range(6,8)

and so on.

Is there a function to loop through in this way?

I don’t want to iterate over non-overlapping chunks, i.e.

range(0,2)
range(4,6) # This is not what I want
range(6,8)

and so on.

Solution

Update: Since Python 3.10, this functionality is built-in. Use itertools.pairwise().

itertools has a nice recipe at the bottom called "pairwise":

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

Example usage:

for x, y in pairwise([1,2,3,4]):
     print(x, y)

1 2
2 3
3 4

Answered By – Bharel

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.