]> granicus.if.org Git - python/commitdiff
Add a prepend() recipe to teach a chain() idiom (GH-6415) (GH-6422)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 8 Apr 2018 21:37:47 +0000 (14:37 -0700)
committerRaymond Hettinger <rhettinger@users.noreply.github.com>
Sun, 8 Apr 2018 21:37:47 +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 3782f40911e27ec6699774c3143209a727b794e4..3739f506f91c351104ac18e0b83fd624d094961d 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 84d11ed6221d810868427d3e667b4ae0a09e914e..9317951d0b6c47bbd00cc77f94bc7e392462a9ce 100644 (file)
@@ -2165,6 +2165,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)
 
@@ -2317,6 +2322,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')]