]> granicus.if.org Git - python/commitdiff
Improve itertools docs with clearer examples of pure python equivalent code.
authorRaymond Hettinger <python@rcn.com>
Sun, 30 Oct 2011 22:06:14 +0000 (15:06 -0700)
committerRaymond Hettinger <python@rcn.com>
Sun, 30 Oct 2011 22:06:14 +0000 (15:06 -0700)
Doc/library/functions.rst
Doc/library/itertools.rst

index ced3745174762e572181d3c6e89110a487ff26ea..e5d4a99c95f11eac7a8eeed57a222f8bfe3409b3 100644 (file)
@@ -1367,10 +1367,10 @@ are always available.  They are listed here in alphabetical order.
         def zip(*iterables):
             # zip('ABCD', 'xy') --> Ax By
             sentinel = object()
-            iterables = [iter(it) for it in iterables]
-            while iterables:
+            iterators = [iter(it) for it in iterables]
+            while iterators:
                 result = []
-                for it in iterables:
+                for it in iterators:
                     elem = next(it, sentinel)
                     if elem is sentinel:
                         return
index 757823d9f1d022a66deeab30a49e8944e8ea5fdf..28625e8834c41b9b476f2d3caebeb098059e4751 100644 (file)
@@ -557,16 +557,25 @@ loops that truncate the stream.
    iterables are of uneven length, missing values are filled-in with *fillvalue*.
    Iteration continues until the longest iterable is exhausted.  Equivalent to::
 
-      def zip_longest(*args, fillvalue=None):
+      class ZipExhausted(Exception):
+          pass
+
+      def zip_longest(*args, **kwds):
           # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
-          def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
-              yield counter()         # yields the fillvalue, or raises IndexError
+          fillvalue = kwds.get('fillvalue')
+          counter = len(args) - 1
+          def sentinel():
+              nonlocal counter
+              if not counter:
+                  raise ZipExhausted
+              counter -= 1
+              yield fillvalue
           fillers = repeat(fillvalue)
-          iters = [chain(it, sentinel(), fillers) for it in args]
+          iterators = [chain(it, sentinel(), fillers) for it in args]
           try:
-              for tup in zip(*iters):
-                  yield tup
-          except IndexError:
+              while iterators:
+                  yield tuple(map(next, iterators))
+          except ZipExhausted:
               pass
 
    If one of the iterables is potentially infinite, then the :func:`zip_longest`