Skip to content

Commit 93a687a

Browse files
authored
Minor clarity improvement for the iter_index() recipe. Also add value subsequence tests. (gh-116696)
1 parent bf121d6 commit 93a687a

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
@@ -902,18 +902,19 @@ which incur interpreter overhead.
902902
# iter_index('AABCADEAF', 'A') --> 0 1 4 7
903903
seq_index = getattr(iterable, 'index', None)
904904
if seq_index is None:
905-
# Slow path for general iterables
905+
# Path for general iterables
906906
it = islice(iterable, start, stop)
907907
for i, element in enumerate(it, start):
908908
if element is value or element == value:
909909
yield i
910910
else:
911-
# Fast path for sequences
911+
# Path for sequences with an index() method
912912
stop = len(iterable) if stop is None else stop
913-
i = start - 1
913+
i = start
914914
try:
915915
while True:
916-
yield (i := seq_index(value, i+1, stop))
916+
yield (i := seq_index(value, i, stop))
917+
i += 1
917918
except ValueError:
918919
pass
919920

@@ -1412,6 +1413,22 @@ The following recipes have a more mathematical flavor:
14121413
>>> ''.join(input_iterator)
14131414
'DEAF'
14141415

1416+
>>> # Verify that the target value can be a sequence.
1417+
>>> seq = [[10, 20], [30, 40], 30, 40, [30, 40], 50]
1418+
>>> target = [30, 40]
1419+
>>> list(iter_index(seq, target))
1420+
[1, 4]
1421+
1422+
>>> # Verify faithfulness to type specific index() method behaviors.
1423+
>>> # For example, bytes and str perform subsequence searches
1424+
>>> # that do not match the general behavior specified
1425+
>>> # in collections.abc.Sequence.index().
1426+
>>> seq = 'abracadabra'
1427+
>>> target = 'ab'
1428+
>>> list(iter_index(seq, target))
1429+
[0, 7]
1430+
1431+
14151432
>>> list(sieve(30))
14161433
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
14171434
>>> 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)