Skip to content

narrow

narrow(
    src: Union[array, list], axis: int, start: int, length: int
) -> Union[array, list, Any]

Returns the length entries of src along axis starting at start.

Parameters:

Name Type Description Default
src Union[array, list]

An array or a list.

required
axis int

The axis along which to slice (must be 0 for lists).

required
start int

Index of the first entry.

required
length int

Number of entries.

required

Returns:

Type Description
Union[array, list, Any]

The slice of src.

Example:

narrow(mx.array([[1, 2, 3], [4, 5, 6]]), 1, 1, 2)
# mx.array([[2, 3], [5, 6]])
Source code in mlx_graphs/utils/indexing.py
def narrow(
    src: Union[mx.array, list], axis: int, start: int, length: int
) -> Union[mx.array, list, Any]:
    """
    Returns the ``length`` entries of ``src`` along ``axis`` starting at
    ``start``.

    Args:
        src: An array or a list.
        axis: The axis along which to slice (must be ``0`` for lists).
        start: Index of the first entry.
        length: Number of entries.

    Returns:
        The slice of ``src``.

    Example:

    .. code-block:: python

        narrow(mx.array([[1, 2, 3], [4, 5, 6]]), 1, 1, 2)
        # mx.array([[2, 3], [5, 6]])
    """
    if isinstance(src, mx.array):
        axis = axis + src.ndim if axis < 0 else axis
        slices = [slice(None)] * src.ndim
        slices[axis] = slice(start, start + length)
        return src[tuple(slices)]
    if isinstance(src, list):
        if axis != 0:
            raise ValueError("Cannot narrow along an axis other than 0 of a list")
        return src[start : start + length]
    raise ValueError(f"Invalid input type (got '{type(src)}')")

from mlx_graphs.utils import narrow · mlx_graphs/utils/indexing.py