Skip to content

Commit eaae563

Browse files
authored
gh-102088 Optimize iter_index itertools recipe (GH-102360)
1 parent 2f62a5d commit eaae563

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

Doc/library/itertools.rst

+6-3
Original file line numberDiff line numberDiff line change
@@ -886,9 +886,12 @@ which incur interpreter overhead.
886886
except AttributeError:
887887
# Slow path for general iterables
888888
it = islice(iterable, start, None)
889-
for i, element in enumerate(it, start):
890-
if element is value or element == value:
891-
yield i
889+
i = start - 1
890+
try:
891+
while True:
892+
yield (i := i + operator.indexOf(it, value) + 1)
893+
except ValueError:
894+
pass
892895
else:
893896
# Fast path for sequences
894897
i = start - 1

Lib/test/test_operator.py

+3
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,9 @@ def test_indexOf(self):
208208
nan = float("nan")
209209
self.assertEqual(operator.indexOf([nan, nan, 21], nan), 0)
210210
self.assertEqual(operator.indexOf([{}, 1, {}, 2], {}), 0)
211+
it = iter('leave the iterator at exactly the position after the match')
212+
self.assertEqual(operator.indexOf(it, 'a'), 2)
213+
self.assertEqual(next(it), 'v')
211214

212215
def test_invert(self):
213216
operator = self.module

0 commit comments

Comments
 (0)