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
enumerate(a[-3:], 3)but not sure why you would have overlooked that, so maybe I'm misunderstanding the question.a. I still don't understand what you mean here. Do you wantenumerate(a, -len(a))perhaps?[3, 4, 5]aren't the indices of the last three items ofa(that is, the items ofathat go into the slice-3:); those would be[2, 3, 4], so you would needenumerate(..., start=1). Is that just an off-by-one error on your part, or do you actually want the elements instead of the indices? If you actually want the elements, then why are you usingenumeratein the first place? I agree with wim, different elements, like strings, would make this clearer.