An "adapter", superset of an iterator

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed May 3 15:46:59 EDT 2023


On Wed, 3 May 2023 at 18:52, Thomas Passin <list1 at tompassin.net> wrote:
>
> On 5/3/2023 5:45 AM, fedor tryfanau wrote:
> > I've been using python as a tool to solve competitive programming problems
> > for a while now and I've noticed a feature, python would benefit from
> > having.
> > Consider "reversed(enumerate(a))". This is a perfectly readable code,
> > except it's wrong in the current version of python. That's because
> > enumerate returns an iterator, but reversed can take only a sequence type.
>
> Depending on what you want to give and receive, enumerate(reversed(a))
> will do the job here.  Otherwise list() or tuple() can achieve some of
> the same things.

I don't think that is equivalent to the intended behaviour:

reversed(enumerate(a)) # zip(reversed(range(len(a))), reversed(a))
enumerate(reversed(a)) # zip(range(len(a)), reversed(a))

In principle for a sequence input enumerate(a) could be something that
behaves like a sequence and therefore could be reiterated or reversed
etc. The enumerate(a).__reversed__ method could then delegate to
a.__reversed__ and a.__len__ if they exist. This could be confusing
though because the possible behaviour of enumerate(a) would be
different depending on the type of a.

--
Oscar


More information about the Python-list mailing list