]> granicus.if.org Git - python/commitdiff
Add a prepend() recipe to teach a chain() idiom (GH-6415) (GH-6421)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 8 Apr 2018 21:37:30 +0000 (14:37 -0700)
committerRaymond Hettinger <rhettinger@users.noreply.github.com>
Sun, 8 Apr 2018 21:37:30 +0000 (14:37 -0700)
(cherry picked from commit 9265dd72e5ec1cfa5fcdb5be8ebffe1d9994bd4b)

Co-authored-by: Raymond Hettinger <rhettinger@users.noreply.github.com>
Doc/library/itertools.rst
Lib/test/test_itertools.py

index a5a5356a9a1fa4dfcfdb39d4110cf67c6224e8bf..959424ff914390e8151089da5dfaa24a8aa9433e 100644 (file)
@@ -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))
index effd7f0e21bec538a5a0e9d010eb59db3d5058da..cbbb4c4f71d3b8d2e8fad564078ee14b0c467291 100644 (file)
@@ -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')]