On Sun, Jan 10, 2021 at 12:29 AM Oscar Benjamin
<[email protected]> wrote:
> I haven't ever wanted to reverse a chain but I have wanted to be able
> to reverse an enumerate many times:
>
> >>> reversed(enumerate([1, 2, 3]))
> ...
> TypeError
>
> The alternative zip(range(len(obj)-1, -1, -1), reversed(obj)) is
> fairly cryptic in comparison as well as probably being less efficient.
> There could be a __reversed__ method for enumerate with the same
> caveat as for chain: if the underlying object is not reversible then
> you get a TypeError. Otherwise reversed(enumerate(seq)) works fine for
> any sequence seq.
To clarify, you want reversed(enumerate(x)) to yield the exact same
pairs that reversed(list(enumerate(x))) would return, yes? If so, it
absolutely must have a length, AND be reversible. I don't think
spelling it reversed(enumerate(x)) will work, due to issues with
partial consumption; but it wouldn't be too hard to define a
renumerate function:
def renumerate(seq):
"""Equivalent to reversed(list(enumerate(seq))) but more efficient"""
return zip(range(len(seq))[::-1], reversed(seq))
(I prefer spelling it [::-1] than risking getting the range args
wrong, but otherwise it's the same as you had)
But if you'd rather not do this, then a cleaner solution might be for
enumerate() to grow a step parameter:
enumerate(iterable, start=0, step=1)
And then, what you want is simply:
enumerate(reversed(seq), len(seq) - 1, -1)
I'm +0 on enumerate gaining a parameter, and otherwise, -1 on actual
changes to the stdlib - this is a one-liner that you can have in your
personal library if you need it. Might be a cool recipe for itertools
docs, or one of the third-party more-itertools packages, or something,
though.
ChrisA
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/5AM7GR2IXPAOHA74RMO7YRF5FGMFKL2P/
Code of Conduct: http://python.org/psf/codeofconduct/