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?
1) Using reverse() method There is an in-built method known as reverse() in python that can reverse the list by changing elements in place of the original list. This method can be used in situations where memory efficiency is required.
Since enumerate() returns a generator and generators can't be reversed, you need to convert it to a list first.
To use the enumerate function in reverse order:Use the enumerate() function to get access to the index when iterating. Convert the enumerate object to a list and reverse the list. Use a for loop to iterate over the list in reverse order.
In Python, a built-in function called reverse() is used to reverse the list. This simple and quick way to reverse a list requires little memory. Syntax: list_name. reverse() Here, list_name means you have to write the list's name, which has to be reversed.
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)
I don't know if this solution is better for you, but at least it's shorter:
>>> [(4 - x, x) for x in range(5)]
[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)]
Just take the length of your list and subtract the index from that...
L = range(5)
for i, n in L:
my_i = len(L) -1 - i
...
Or if you really need a generator:
def reverse_enumerate(L):
# Only works on things that have a len()
l = len(L)
for i, n in enumerate(L):
yield l-i-1, n
enumerate()
can't possibly do this, as it works with generic iterators. For instance, you can pass it infinite iterators, that don't even have a "reverse index".
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