[Python-checkins] Add a prepend() recipe to teach a chain() idiom (GH-6415) (GH-6422)
Raymond Hettinger
webhook-mailer at python.org
Sun Apr 8 17:37:50 EDT 2018
https://github.com/python/cpython/commit/280a767d02c778a33ffb3347ac7cb89b35e41c51
commit: 280a767d02c778a33ffb3347ac7cb89b35e41c51
branch: 3.6
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: Raymond Hettinger <rhettinger at users.noreply.github.com>
date: 2018-04-08T14:37:47-07:00
summary:
Add a prepend() recipe to teach a chain() idiom (GH-6415) (GH-6422)
(cherry picked from commit 9265dd72e5ec1cfa5fcdb5be8ebffe1d9994bd4b)
Co-authored-by: Raymond Hettinger <rhettinger at users.noreply.github.com>
files:
M Doc/library/itertools.rst
M Lib/test/test_itertools.py
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index 3782f40911e2..3739f506f91c 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 84d11ed6221d..9317951d0b6c 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -2165,6 +2165,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)
@@ -2317,6 +2322,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')]
More information about the Python-checkins
mailing list