Skip to content

Commit 9f38686

Browse files
[3.12] Minor clarity improvement for the iter_index() recipe. Also add value subsequence tests. (gh-116696) (gh-116698)
1 parent 84c8925 commit 9f38686

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

Doc/library/itertools.rst

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -894,18 +894,19 @@ which incur interpreter overhead.
894894
# iter_index('AABCADEAF', 'A') --> 0 1 4 7
895895
seq_index = getattr(iterable, 'index', None)
896896
if seq_index is None:
897-
# Slow path for general iterables
897+
# Path for general iterables
898898
it = islice(iterable, start, stop)
899899
for i, element in enumerate(it, start):
900900
if element is value or element == value:
901901
yield i
902902
else:
903-
# Fast path for sequences
903+
# Path for sequences with an index() method
904904
stop = len(iterable) if stop is None else stop
905-
i = start - 1
905+
i = start
906906
try:
907907
while True:
908-
yield (i := seq_index(value, i+1, stop))
908+
yield (i := seq_index(value, i, stop))
909+
i += 1
909910
except ValueError:
910911
pass
911912

@@ -1400,6 +1401,22 @@ The following recipes have a more mathematical flavor:
14001401
>>> ''.join(input_iterator)
14011402
'DEAF'
14021403

1404+
>>> # Verify that the target value can be a sequence.
1405+
>>> seq = [[10, 20], [30, 40], 30, 40, [30, 40], 50]
1406+
>>> target = [30, 40]
1407+
>>> list(iter_index(seq, target))
1408+
[1, 4]
1409+
1410+
>>> # Verify faithfulness to type specific index() method behaviors.
1411+
>>> # For example, bytes and str perform subsequence searches
1412+
>>> # that do not match the general behavior specified
1413+
>>> # in collections.abc.Sequence.index().
1414+
>>> seq = 'abracadabra'
1415+
>>> target = 'ab'
1416+
>>> list(iter_index(seq, target))
1417+
[0, 7]
1418+
1419+
14031420
>>> list(sieve(30))
14041421
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
14051422
>>> small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

0 commit comments

Comments
 (0)