Python enumerate reverse index only

rozzy picture rozzy · Aug 3, 2016 · Viewed 25.9k times · Source

I am trying to reverse the index given by enumerate whilst retaining the original order of the list being enumerated.

Assume I have the following:

>> range(5)
[0, 1, 2, 3, 4]

If I enumerate this I would get the following:

>> list(enumerate(range(5)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

However I want to reverse the index provided by enumerate so that I get:

[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)]

So far I have the following code:

reversed(list(enumerate(reversed(range(5)))))

I was just wondering if there was a neater way to do this?

Answer

Netwave picture Netwave · Aug 3, 2016

How about using zip instead with a reversed range?

>>> zip(range(9, -1, -1), range(10))
[(9, 0), (8, 1), (7, 2), (6, 3), (5, 4), (4, 5), (3, 6), (2, 7), (1, 8), (0, 9)]


>>> def reversedEnumerate(l):
        return zip(range(len(l)-1, -1, -1), l)
>>> reversedEnumerate(range(10))
[(9, 0), (8, 1), (7, 2), (6, 3), (5, 4), (4, 5), (3, 6), (2, 7), (1, 8), (0, 9)]

As @julienSpronk suggests, use izip to get a generator, also xrange:

import itertools
>>> import itertools
>>> def reversedEnumerate(l):
...     return itertools.izip(xrange(len(l)-1, -1, -1), l)
...     
>>> reversedEnumerate(range(10))
<itertools.izip object at 0x03749760>
>>> for i in reversedEnumerate(range(10)):
...     print i
...     
(9, 0)
(8, 1)
(7, 2)
(6, 3)
(5, 4)
(4, 5)
(3, 6)
(2, 7)
(1, 8)
(0, 9)