While searching the Python Documentation I found the equivalent python implementation of Pythons build-in zip()
function.
Instead of catching a StopIteration
exception which signals that there are no further items produced by the iterator the author(s) use an if
statement to check if the returned default value form next()
equals object()
("sentinel
") and stop the generator:
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)
I wonder now if there is any difference between the exception catching or an if
statement as used by the Python Docs?
Or better, as @hiro protagonist pointed out:
What's wrong with using a try
statement considering EAFP (Easier to ask for forgiveness than permission) in Python?
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
try:
elem = next(it)
except StopIteration:
return
result.append(elem)
yield tuple(result)
Also as Stoyan Dekov mentioned "A try/except block is extremely efficient if no exceptions are raised. Actually catching an exception is expensive." (see the docs for more information)
But an exception would only occur once, namely as soon as the iterator is exhausted. So exception handling would be the better solution in this case?