Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use enumerate to count backwards?

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
like image 615
Craig Avatar asked May 17 '18 01:05

Craig


People also ask

How do you reverse a list in enumerate?

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.

How do you enumerate backwards in Python?

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.

How do you count backwards and range 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.


1 Answers

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.
  • Finally we use abs on idx 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
like image 122
rudevdr Avatar answered Oct 02 '22 21:10

rudevdr