On Sat, Jan 18, 2014 at 4:50 AM, Peter Otten <__pete...@web.de> wrote: > > PS: There is an odd difference in the behaviour of list-comps and generator > expressions. The latter swallow Stopiterations which is why the above > myzip() needs the len() test:
A comprehension is building a list in a `for` loop, which won't swallow a `StopIteration` from the body of the loop itself. For a generator, an unhandled `StopIteration` propagates to the frame that called `__next__`. In this case the tuple constructor swallows the `StopIteration`, as it rightly should. There's no way for it know the original source of the `StopIteration` exception. You'd have to use a generator that translates `StopIteration` to a custom exception. Then use that exception to `break` the `while` loop. But no one sane would go that far. >>>> def myzip(*iterables): > ... iterators = [iter(it) for it in iterables] > ... while True: > ... t = [next(it) for it in iterators] > ... yield tuple(t) The C implementation for `zip.__next__` calls `PyTuple_SET_ITEM` in a loop over the iterators. It reuses the same tuple so long as the reference count is only 1. That can't be duplicated in pure Python. You'd have to use a `list`. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor