'What is the most pythonic way to have inverse enumerate of a list?
The first thing that comes to mind is:
>>> l = list('abcdef')
>>> for i in range(len(l)-1, -1, -1):
... item = l[i]
... print(i, item)
...
5 f
4 e
3 d
2 c
1 b
0 a
I tried using the following:
>>> l
['a', 'b', 'c', 'd', 'e', 'f']
>>> for i,ch in reversed(enumerate(l)):
... print(i,ch)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'enumerate' object is not reversible
but apparently 'enumerate' object is not reversible. I can trick it with:
>>> for i,ch in reversed(list(enumerate(l))):
... print(i,ch)
...
5 f
4 e
3 d
2 c
1 b
0 a
but that doesn't feel right - it's a bit cumbersome. Is there a better way to do this? Maybe some inverse_enumerate
hidden is a lib like collections or itertools?
Solution 1:[1]
That might not be the most pythonic approach, but you could reuse the code provided by the documentation on enumerate
to re-implement your own reversed enumerate
.
The doc provides the following code:
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
Here is a proposal for a renumerate
function, that yields elements of a sequence in the reversed order:
def renumerate(sequence, start=None):
n = start
if start is None:
start = len(sequence) - 1
for elem in sequence[::-1]:
yield n, elem
n -= 1
Unfortunately, this will not work with generators, since it requires knowing the length of the sequence.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Right leg |