Mirzhan Irkegulov Mirzhan Irkegulov - 11 days ago 6
Python Question

Python enumerate downwards or with a custom step

How to make Python's

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

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 The Python yield keyword explained and Difference between Python Generators vs Iterators.

Comments