diff options
author | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2018-04-08 15:44:20 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-04-08 15:44:20 (GMT) |
commit | 9265dd72e5ec1cfa5fcdb5be8ebffe1d9994bd4b (patch) | |
tree | 59d0c55bcf779aa2cc55b1f47b64682df78edebb | |
parent | c87eb09d2e3783b0b5dc0d7cb304050cbcc86ad3 (diff) | |
download | cpython-9265dd72e5ec1cfa5fcdb5be8ebffe1d9994bd4b.zip cpython-9265dd72e5ec1cfa5fcdb5be8ebffe1d9994bd4b.tar.gz cpython-9265dd72e5ec1cfa5fcdb5be8ebffe1d9994bd4b.tar.bz2 |
Add a prepend() recipe to teach a chain() idiom (GH-6415)
-rw-r--r-- | Doc/library/itertools.rst | 5 | ||||
-rw-r--r-- | Lib/test/test_itertools.py | 8 |
2 files changed, 13 insertions, 0 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index a5a5356..959424f 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 effd7f0..cbbb4c4 100644 --- a/Lib/test/test_itertools.py +++ b/Lib/test/test_itertools.py @@ -2198,6 +2198,11 @@ Samuele ... "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 @@ perform as purported. >>> 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')] |