Skip to content

Commit 3effcce

Browse files
[3.11] gh-102088 Optimize iter_index itertools recipe (GH-102360) (GH-102363)
1 parent 90ec292 commit 3effcce

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

Doc/library/itertools.rst

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -875,9 +875,12 @@ which incur interpreter overhead.
875875
except AttributeError:
876876
# Slow path for general iterables
877877
it = islice(iterable, start, None)
878-
for i, element in enumerate(it, start):
879-
if element is value or element == value:
880-
yield i
878+
i = start - 1
879+
try:
880+
while True:
881+
yield (i := i + operator.indexOf(it, value) + 1)
882+
except ValueError:
883+
pass
881884
else:
882885
# Fast path for sequences
883886
i = start - 1

Lib/test/test_operator.py

Lines changed: 3 additions & 0 deletions
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)