Skip to content

Commit 9265dd7

Browse files
authored
Add a prepend() recipe to teach a chain() idiom (GH-6415)
1 parent c87eb09 commit 9265dd7

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

Doc/library/itertools.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -688,6 +688,11 @@ which incur interpreter overhead.
688688
"Return first n items of the iterable as a list"
689689
return list(islice(iterable, n))
690690

691+
def prepend(value, iterator):
692+
"Prepend a single value in front of an iterator"
693+
# prepend(1, [2, 3, 4]) -> 1 2 3 4
694+
return chain([value], iterator)
695+
691696
def tabulate(function, start=0):
692697
"Return function(0), function(1), ..."
693698
return map(function, count(start))

Lib/test/test_itertools.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2198,6 +2198,11 @@ def test_permutations_sizeof(self):
21982198
... "Return first n items of the iterable as a list"
21992199
... return list(islice(iterable, n))
22002200
2201+
>>> def prepend(value, iterator):
2202+
... "Prepend a single value in front of an iterator"
2203+
... # prepend(1, [2, 3, 4]) -> 1 2 3 4
2204+
... return chain([value], iterator)
2205+
22012206
>>> def enumerate(iterable, start=0):
22022207
... return zip(count(start), iterable)
22032208
@@ -2350,6 +2355,9 @@ def test_permutations_sizeof(self):
23502355
>>> take(10, count())
23512356
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
23522357
2358+
>>> list(prepend(1, [2, 3, 4]))
2359+
[1, 2, 3, 4]
2360+
23532361
>>> list(enumerate('abc'))
23542362
[(0, 'a'), (1, 'b'), (2, 'c')]
23552363

0 commit comments

Comments
 (0)