reversed(enumerate(x))

Chris Angelico rosuav at gmail.com
Wed Jul 20 13:46:56 EDT 2016


On Thu, Jul 21, 2016 at 3:42 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> I had occasion to write something like this:
>
>     for i, n in reversed(enumerate(x)): pass
>
> Of course this fails with "TypeError: argument to reversed() must be a
> sequence". I ended up using this instead:
>
>     for i, n in zip(reversed(range(len(x))), reversed(x)): pass

At the cost of coalescing the enumeration, you could:

for i, n in reversed(list(enumerate(x))): pass

It's reasonably clean but less efficient.

ChrisA



More information about the Python-list mailing list