def _nest(stack):
    "Build recursive loops and iterate over tuples on the stack."
    top = stack.pop()
    if stack:
        for v1 in top:
            for v2 in _nest(stack):
                yield (v1,) + v2
    else:
        for value in top:
            yield (value,)
    stack.append(top)
Build recursive loops and iterate over tuples on the stack.
recipes/Python/578046_Easily_Write_Nested_Loops/recipe-578046.py