-3

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 
5
  • I think it's enumerate(a[-3:], 3) but not sure why you would have overlooked that, so maybe I'm misunderstanding the question. Commented Jan 13, 2021 at 5:06
  • Yes, I want to do it only using negative indices. Commented Jan 13, 2021 at 5:14
  • I'm not sure I understand what you're looking for. Could you edit the question to include the output you want? Commented Jan 13, 2021 at 5:23
  • 1
    Maybe it would be clearer if you use strings instead of numbers in a. I still don't understand what you mean here. Do you want enumerate(a, -len(a)) perhaps? Commented Jan 13, 2021 at 5:24
  • [3, 4, 5] aren't the indices of the last three items of a (that is, the items of a that go into the slice -3:); those would be [2, 3, 4], so you would need enumerate(..., 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 using enumerate in the first place? I agree with wim, different elements, like strings, would make this clearer. Commented Aug 4 at 13:46

2 Answers 2

0
>>> [c for c, i in enumerate(a[-3:], -3)] [-3, -2, -1] 

you should get i not c

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

c is the index, i is the value in array.

Sign up to request clarification or add additional context in comments.

Comments

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

With enumerate:

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

8 Comments

This is is clear but my question is how to get this slice enumerated.
You want to specifically use enumerate. With no more goal than this? See my edit.
Why would anyone do this? It's the same as a[-3:].
The OP wants. So the OP is right. Still I concede ;)
(i, j)[1]??? Why are you creating a tuple there? Just use j instead.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.