Personally I like mark_ends
from the third party library more-itertools
from more_itertools import mark_ends
i = SomeIndex()
for first, last, elem in mark_ends(mylist[i:]):
if elem == name:
return
if first:
foo()
mark_ends
gives you a 3-tuple for every element in your iterable, in this case the sliced mylist
. The tuples are (True, False, elem_0), (False, False, elem_1), ..., (False, False, elem_n-2), (False, True, elem_n-1)
. In your use case you never use the middle element of the tuples.
If for some reason you can't or don't want to use the external library you can swipe the code from https://more-itertools.readthedocs.io/en/stable/_modules/more_itertools/more.html#mark_ends
Addendum:
In light of the OP's requirement to let foo
change the list, here's a quick modification:
from more_itertools import mark_ends
i = SomeIndex()
for first, last, (j, elem) in mark_ends(enumerate(mylist[i:], start=i)):
if elem == name:
return
if first:
foo(mylist, j)
j
now gives you the index that you need to tell foo
what to change.