From c2bfcb1b7c22bd5bb6dbe2118d7e1c9a0d0eef9a Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Sat, 7 Apr 2018 17:34:35 -0700 Subject: [PATCH 1/2] Add a prepend() recipe to teach a chain() idiom --- 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 a5a5356a9a1fa4..a5c223677113e7 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 effd7f0e21bec5..cbbb4c4f71d3b8 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')] From bf48b0088fa1942e7273b5f482d4295d7f197ee1 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Sun, 8 Apr 2018 10:02:30 +0300 Subject: [PATCH 2/2] Remove trailing spaces. --- Doc/library/itertools.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index a5c223677113e7..959424ff914390 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -692,7 +692,7 @@ which incur interpreter overhead. "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))