Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

413
Vistas
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?

Thanks.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda