#StackBounty: #python #indexing #tuples #pairwise Finding index of pairwise elements

Bounty: 50

Given the target `('b', 'a')` and the inputs:

``````x0 = ('b', 'a', 'z', 'z')
x1 = ('b', 'a', 'z', 'z')
x2 = ('z', 'z', 'a', 'a')
x3 = ('z', 'b', 'a', 'a')
``````

The aim to find the location of the continuous `('b', 'a')` element and get the output:

``````>>> find_ba(x0)
0
>>> find_ba(x1)
0
>>> find_ba(x2)
None
>>> find_ab(x3)
1
``````

Using the `pairwise` recipe:

``````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)
``````

I could do this to get the desired output:

``````def find_ba(x, target=('b', 'a')):
try:
return next(i for i, pair in enumerate(pairwise(x)) if pair == target)
except StopIteration:
return None
``````

But that would require me to loop through all pairs of characters till I find the first instance. Is there a way to finding index of pairwise elements without looping all the characters?