Mirzhan Irkegulov Mirzhan Irkegulov - 1 year ago 106
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

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

Answer Source

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


>>> 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download