Hi,

I needed reversed(enumerate(x: list)) in my code, and have discovered that
it wound't work. This is disappointing because operation is well defined.
It is also well defined for str type, range, and - in principle, but not
yet in practice - on dictionary iterators - keys(), values(), items() as
dictionaries are ordered now.
It would also be well defined on any user type implementing __iter__,
__len__, __reversed__ - think numpy arrays, some pandas dataframes, tensors.

That's plenty of usecases, therefore I guess it would be quite useful to
avoid hacky / inefficient solutions like described here:
https://code.activestate.com/lists/python-list/706205/.

If deemed useful, I would be interested in implementing this, maybe
together with __reversed__ on dict keys, values, items.

Best Regards,
--
Ilya Kamen

-----------
p.s.

*Sketch* of what I am proposing:

class reversible_enumerate:

    def __init__(self, iterable):
        self.iterable = iterable
        self.ctr = 0

    def __iter__(self):
        for e in self.iterable:
            yield self.ctr, e
            self.ctr += 1

    def __reversed__(self):
        try:
            ri = reversed(self.iterable)
        except Exception as e:
            raise Exception(
                "enumerate can only be reversed if iterable to
enumerate can be reversed and has defined length."
            ) from e

        try:
            l = len(self.iterable)
        except Exception as e:
            raise Exception(
                "enumerate can only be reversed if iterable to
enumerate can be reversed and has defined length."
            ) from e

        indexes = range(l-1, -1, -1)
        for i, e in zip(indexes, ri):
            yield i, e

for i, c in reversed(reversible_enumerate("Hello World")):
    print(i, c)

for i, c in reversed(reversible_enumerate([11, 22, 33])):

    print(i, c)
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/python-dev@python.org/message/NDDKDUDHE3J7SR7IPO3QXCVFSGE4BAV4/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to