[Python-checkins] gh-102088 Optimize iter_index itertools recipe (GH-102360)

rhettinger webhook-mailer at python.org
Wed Mar 1 22:16:47 EST 2023


https://github.com/python/cpython/commit/eaae563b6878aa050b4ad406b67728b6b066220e
commit: eaae563b6878aa050b4ad406b67728b6b066220e
branch: main
author: Stefan Pochmann <609905+pochmann at users.noreply.github.com>
committer: rhettinger <rhettinger at users.noreply.github.com>
date: 2023-03-01T21:16:23-06:00
summary:

gh-102088 Optimize iter_index itertools recipe (GH-102360)

files:
M Doc/library/itertools.rst
M Lib/test/test_operator.py

diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index 95da7166842e..d85a17effb04 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -886,9 +886,12 @@ which incur interpreter overhead.
        except AttributeError:
            # Slow path for general iterables
            it = islice(iterable, start, None)
-           for i, element in enumerate(it, start):
-               if element is value or element == value:
-                   yield i
+           i = start - 1
+           try:
+               while True:
+                   yield (i := i + operator.indexOf(it, value) + 1)
+           except ValueError:
+               pass
        else:
            # Fast path for sequences
            i = start - 1
diff --git a/Lib/test/test_operator.py b/Lib/test/test_operator.py
index b7e38c233498..1db738d228b1 100644
--- a/Lib/test/test_operator.py
+++ b/Lib/test/test_operator.py
@@ -208,6 +208,9 @@ def test_indexOf(self):
         nan = float("nan")
         self.assertEqual(operator.indexOf([nan, nan, 21], nan), 0)
         self.assertEqual(operator.indexOf([{}, 1, {}, 2], {}), 0)
+        it = iter('leave the iterator at exactly the position after the match')
+        self.assertEqual(operator.indexOf(it, 'a'), 2)
+        self.assertEqual(next(it), 'v')
 
     def test_invert(self):
         operator = self.module



More information about the Python-checkins mailing list