Python enumerate downwards or with a custom step

Mirzhan Irkegulov picture Mirzhan Irkegulov · Jun 18, 2014 · Viewed 10.5k times · Source

How to make Python's enumerate function to enumerate from bigger numbers to lesser (descending order, decrement, count down)? Or in general, how to use different step increment/decrement in enumerate?

For example, such function, applied to list ['a', 'b', 'c'], with start value 10 and step -2, would produce iterator [(10, 'a'), (8, 'b'), (6, 'c')].

Answer

Mirzhan Irkegulov picture Mirzhan Irkegulov · Jun 18, 2014

I haven't found more elegant, idiomatic, and concise way, than to write a simple generator:

def enumerate2(xs, start=0, step=1):
    for x in xs:
        yield (start, x)
        start += step

Examples:

>>> list(enumerate2([1,2,3], 5, -1))
[(5, 1), (4, 2), (3, 3)]
>>> list(enumerate2([1,2,3], 5, -2))
[(5, 1), (3, 2), (1, 3)]

If you don't understand the above code, read What does the "yield" keyword do in Python? and Difference between Python's Generators and Iterators.