Craig
Craig

Reputation: 593

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

Upvotes: 16

Views: 11418

Answers (8)

rudevdr
rudevdr

Reputation: 439

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

Upvotes: 22

letters = ['a', 'b', 'c']

for i, letter in zip(range(len(letters)-1, -1, -1), letters):
    print(i, letter)

prints

2 a
1 b
0 c

Taken from answer in a similar question: Traverse a list in reverse order in Python

Upvotes: 1

Azat Ibrakov
Azat Ibrakov

Reputation: 10990

We can define utility function (in Python3.3+)

from itertools import count


def enumerate_ext(iterable, start=0, step=1):
    indices = count(start, step)
    yield from zip(indices, iterable)

and use it directly like

letters = ['a', 'b', 'c']
for index, letter in enumerate_ext(letters,
                                   start=len(letters) - 1,
                                   step=-1):
    print(index, letter)

or write helper

def reverse_enumerate(sequence):
    yield from enumerate_ext(sequence,
                             start=len(sequence) - 1,
                             step=-1)

and use it like

for index, letter in reverse_enumerate(letters):
    print(index, letter)

Upvotes: 0

CathyQian
CathyQian

Reputation: 1159

Try this:

l = len(letters)
for i, letter in enumerate(letters):
    print(l-i, letters)

Upvotes: 3

Justin
Justin

Reputation: 61

The zip function creates a list of element-wise pairs for two parameter lists.

list(zip([i for i in range(len(letters))][::-1], letters))

Upvotes: 1

Ashlou
Ashlou

Reputation: 694

I would try to make a reverse list first then you may use enumerate()

letters = ['a', 'b', 'c']
letters.reverse()
for i, letter in enumerate(letters)

Upvotes: 1

Hello World
Hello World

Reputation: 395

tl;dr: size - index - 1

I'll assume the question you are asking is whether or not you can have the index be reversed while the item is the same, for example, the a has the ordering number of 2 when it actually has an index of 0.

To calculate this, consider that each element in your array or list wants to have the index of the item with the same "distance" (index wise) from the end of the collection. Calculating this gives you size - index.

However, many programming languages start arrays with an index of 0. Due to this, we would need to subtract 1 in order to make the indices correspond properly. Consider our last element, with an index of size - 1. In our original equation, we would get size - (size - 1), which is equal to size - size + 1, which is equal to 1. Therefore, we need to subtract 1.

Final equation (for each element): size - index - 1

Upvotes: 0

Vivek Pabani
Vivek Pabani

Reputation: 452

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

Upvotes: 4

Related Questions