yield break in Python
A good way to handle this is raising StopIteration which is what is raised when your iterator has nothing left to yield and next()
is called. This will also gracefully break out of a for loop with nothing inside the loop executed.
For example, given a tuple (0, 1, 2, 3)
I want to get overlapping pairs ((0, 1), (1, 2), (2, 3))
. I could do it like so:
def pairs(numbers): if len(numbers) < 2: raise StopIteration for i, number in enumerate(numbers[1:]): yield numbers[i], number
Now pairs
safely handles lists with 1 number or less.