[Python] Enumerate a slice with negative indices

Discussão em 'Python' iniciado por Stack, Agosto 4, 2025.

  1. Stack

    Stack Membro Participativo

    I want to iterate over and enumerate the last few items of a list:

    >>> a = [1, 2, 3, 4, 5]
    >>> [c for c, i in enumerate(a[-3:], -3)]
    [-3, -2, -1]
    >>> [c for c, i in enumerate(list(a[-3:]))]
    [0, 1, 2]
    >>> [c for c, i in islice(enumerate(a), -5)]
    ValueError: Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.


    So how do I get enumerated [3, 4, 5] using negative indices?

    Example:

    for i, j in enumerate(...):
    print(i, j)


    where ... contains a slice expression with only negative indices should give:

    0 3
    1 4
    2 5

    Continue reading...

Compartilhe esta Página