Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of comparing all adjacent elements in a list

I want to know if there's a more Pythonic way of doing the following:

A = some list
i = 0
j = 1
for _ in range(1, len(A)):
    #some operation between A[i] and A[j]
    i += 1
    j += 1

I feel like this should/could be done differently. Ideas?

EDIT: Since some are asking for requirements. I wanted a general-purpose answer. Maybe to check if A[i], A[j] are between a certain range, or if they're equal. Or maybe I wanted to do a "trickle-up" of elements. The more general, the better.

like image 228
lorenzocastillo Avatar asked Apr 11 '16 13:04

lorenzocastillo


2 Answers

There's a nice little recipe in itertools for doing this. As a bonus it works with any iterable, not just sequences.

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)

for current, next_ in pairwise(A):
    # do something
    pass

If you need the index as well then just enumerate the pairwise iterator.

for current_index, (current, next_) in enumerate(pairwise(A)):
    # do something
    pass
like image 57
Dunes Avatar answered Sep 20 '22 22:09

Dunes


zip lets you combine multiple iterators:

for i,j in zip(range(0,len(A)-1), range(1,len(A))):
    #some operation between A[i] and A[j]

you can also use enumerate on a range object:

for i,j in enumerate(range(1,len(A)):
    #some operation between A[i] and A[j]

Note that unlike the other answers this gives you access to the indices of A not just the items, this is necessary if you want to use any assignment to A[i] or A[j], for example here is a very basic bubble sort:

A = list(range(10))
found1=True
while found1:
    found1=False
    for i,j in enumerate(range(1,len(A))):
        if A[i] < A[j]:
            A[i],A[j] = A[j],A[i]
            found1=True
print(A)

this is only possible when you iterate over the indices of A.

like image 33
Tadhg McDonald-Jensen Avatar answered Sep 17 '22 22:09

Tadhg McDonald-Jensen