import itertools


def multiindex_iterator (shape, *, melt_1_tuple=False):
    """
    Provides a tuple-valued iterator to iterate over all multi-indices with given shape.
    For example, if shape is (2,3), then the iterated sequence is:

        (0,0), (0,1), (0,2), (1,0), (1,1), (1,2).

    If len(shape) is 1 and melt_1_tuple is True (the default is False), then instead of
    returning single-element tuples (0,), (1,), (2,), ..., (n-1,), it returns the plain-old
    integer sequence

        0, 1, 2, ..., n-1.

    Note that if len(shape) is 0, then the iterable sequence will be a single, empty tuple.
    """
    if len(shape) == 1 and melt_1_tuple:
        return range(shape[0])
    else:
        return itertools.product(*map(range, shape))