pythonslicepython-itertoolsenumeration

Enumerate a slice with negative indices


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

Solution

  • >>> [c for c in a[-3:]]
    [3, 4, 5]
    

    With enumerate:

    >>> [(i, j)[1] for i, j in enumerate(a[-3:])]
    [3, 4, 5]