From 9265dd72e5ec1cfa5fcdb5be8ebffe1d9994bd4b Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Sun, 8 Apr 2018 08:44:20 -0700 Subject: [PATCH] Add a prepend() recipe to teach a chain() idiom (GH-6415) --- Doc/library/itertools.rst | 5 +++++ Lib/test/test_itertools.py | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index a5a5356a9a1..959424ff914 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -688,6 +688,11 @@ which incur interpreter overhead. "Return first n items of the iterable as a list" return list(islice(iterable, n)) + def prepend(value, iterator): + "Prepend a single value in front of an iterator" + # prepend(1, [2, 3, 4]) -> 1 2 3 4 + return chain([value], iterator) + def tabulate(function, start=0): "Return function(0), function(1), ..." return map(function, count(start)) diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py index effd7f0e21b..cbbb4c4f71d 100644 --- a/Lib/test/test_itertools.py +++ b/Lib/test/test_itertools.py @@ -2198,6 +2198,11 @@ def test_permutations_sizeof(self): ... "Return first n items of the iterable as a list" ... return list(islice(iterable, n)) +>>> def prepend(value, iterator): +... "Prepend a single value in front of an iterator" +... # prepend(1, [2, 3, 4]) -> 1 2 3 4 +... return chain([value], iterator) + >>> def enumerate(iterable, start=0): ... return zip(count(start), iterable) @@ -2350,6 +2355,9 @@ def test_permutations_sizeof(self): >>> take(10, count()) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +>>> list(prepend(1, [2, 3, 4])) +[1, 2, 3, 4] + >>> list(enumerate('abc')) [(0, 'a'), (1, 'b'), (2, 'c')]