How can I use enumerate to count backwards?
Try this:
letters = ['a', 'b', 'c']
for i, letter in reversed(list(enumerate(reversed(letters)))):
print(i, letter)
Output:
2 a
1 b
0 c
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
'sstart
arg is given a negative value.enumerate
always takes a step forward.- Finally we use
abs
onidx
to find absolute value, which is always positive. - If you want to start indexing from zero then use
-len(items) + 1
to fix off-by-one error