3 ms·
A simpler (IMHO) Python version, plus lazy and working on any iterable. Also, it's quite easy to adapt it to work on any number of iterables. def myzip(x,
by krab 4y ago
A simpler (IMHO) Python version, plus lazy and working on any iterable. Also, it's quite easy to adapt it to work on any number of iterables.
def myzip(x, y):
x, y = iter(x), iter(y)
try:
while True:
yield next(x), next(y)
except StopIteration:
return
- greenpeas 4y agoI was looking for a way to implement this more pythonically. And this looks great. But it made me think that if x and y are of different lengths, the last iteration might consume an element out of the longer iterator. So I tried it with the builtin `zip(a,b)`, and indeed, if a is shorter, `zip(a,b)` consumes the same number of elements from both a and b. But if a is longer, then `zip(a,b)` consumes one extra element from a. I don't know if this behavior is well defined, that is whether I can rely on this, or the order of evaluation of the arguments of a function is up to the interpreter/compiler, and may change. masklinn wrote a comment in another thread about this that i didn't understand until I saw your implementation.
- Joker_vD 4y agodef myzip(*seqs): next_yield = [None] * len(seqs) its = [iter(seq) for seq in seqs] should_go = True while should_go: for index, it in enumerate(its): try: next_yield[index] = next(it) except StopIteration: should_go = False if should_go: yield tuple(next_yield) It consumes exactly the same number of elements from all sequences, unless a non-StopIteration exception occurs during the iteration.