Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most pythonic way to have inverse enumerate of a list? [duplicate]

Tags:

python

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?

Thanks.

like image 983
Iliyan Bobev Avatar asked Feb 15 '18 12:02

Iliyan Bobev


Video Answer


1 Answers

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.

like image 171
Right leg Avatar answered Oct 07 '22 23:10

Right leg