Skip to content

Commit 280a767

Browse files
Add a prepend() recipe to teach a chain() idiom (pythonGH-6415) (pythonGH-6422)
(cherry picked from commit 9265dd7) Co-authored-by: Raymond Hettinger <rhettinger@users.noreply.github.com>
1 parent b603609 commit 280a767

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
@@ -2165,6 +2165,11 @@ def test_permutations_sizeof(self):
21652165
... "Return first n items of the iterable as a list"
21662166
... return list(islice(iterable, n))
21672167
2168+
>>> def prepend(value, iterator):
2169+
... "Prepend a single value in front of an iterator"
2170+
... # prepend(1, [2, 3, 4]) -> 1 2 3 4
2171+
... return chain([value], iterator)
2172+
21682173
>>> def enumerate(iterable, start=0):
21692174
... return zip(count(start), iterable)
21702175
@@ -2317,6 +2322,9 @@ def test_permutations_sizeof(self):
23172322
>>> take(10, count())
23182323
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
23192324
2325+
>>> list(prepend(1, [2, 3, 4]))
2326+
[1, 2, 3, 4]
2327+
23202328
>>> list(enumerate('abc'))
23212329
[(0, 'a'), (1, 'b'), (2, 'c')]
23222330

0 commit comments

Comments
 (0)