letters = ['a', 'b', 'c']
Assume this is my list. Where for i, letter in enumerate(letters)
would be:
0, a
1, b
2, c
How can I instead make it enumerate backwards, as:
2, a
1, b
0, c
reverse() ; if you need a copy of the list in reversed order use alist[::-1] . in this answer though, list(enumerate(a)) DOES create a copy. @ JF, reversed() doesn't make a copy, but list(enumerate()) DOES make a copy.
Using extended slicing The [::-1] slice makes a copy of the list in reverse order, which can be used in the for-loop to print items in reverse order. That's all about traversing a list in reverse order in Python.
If you wrap range() inside reversed() , then you can print the integers in reverse order. range() makes it possible to iterate over a decrementing sequence of numbers, whereas reversed() is generally used to loop over a sequence in reverse order.
This is a great solution and works perfectly:
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
for idx, item in enumerate(items, start=-len(items)):
print(f"reverse index for {item}: {abs(idx)}")
Here is the OUTPUT of the above snippet:
reverse index for a: 7
reverse index for b: 6
reverse index for c: 5
reverse index for d: 4
reverse index for e: 3
reverse index for f: 2
reverse index for g: 1
Here is what happening in above snippet:
enumerate
's start
arg is given a negative value.enumerate
always takes a step forward.abs
on idx
to find absolute value, which is always positive.-len(items) + 1
to fix off-by-one error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With