[Python] How does Python parse `:,` when used to slice/index a NumPy array?

Discussão em 'Python' iniciado por Stack, Julho 22, 2025.

  1. Stack

    Stack Membro Participativo

    When giving numbers, like array[0, 0], Python treats 0, 0 as a tuple. But I'm confused how array[:, 0] is not a syntax error.
    I can't think of a case where a colon followed by a comma is valid in python outside of NumPy.

    I had a few ideas on tricks NumPy may be using, but they were all wrong:
    :), 0), [:, 0], {:, 0} and :, 0 are all invalid Python
    : and , can't be used as variable names.
    : and , aren't operators that could be overloaded.
    It's not python's [start:stop:step] slicing syntax with some trick to allow the comma, because it couldn't explain the 3rd colon in array[:, :, :]

    I'm stumped on how this syntax works. How is Python parsing it?

    Continue reading...

Compartilhe esta Página