On Fri, Jan 22, 2021 at 5:44 AM Neil Girdhar <mistersh...@gmail.com> wrote:
>
> On Thu, Jan 21, 2021 at 1:26 PM Chris Angelico <ros...@gmail.com> wrote:
> >
> > On Fri, Jan 22, 2021 at 5:21 AM Neil Girdhar <mistersh...@gmail.com> wrote:
> > >
> > > I've seen this proposed here before.  The general idea is that some 
> > > iterator transformations (like enumerate) should return sequences when 
> > > they're applied to sequences.  I think it's good idea, but it adds 
> > > complexity and work, which I guess needs to be justified on a 
> > > case-by-case basis.
> > >
> > > In short, this has nothing to do with reversed.  If you made enumerate 
> > > return a sequence when its input is a sequence, you would also be able to 
> > > do enumerate(some_list)[34], which could also be useful.  I think it 
> > > makes Python slightly more perfect and more beautiful.
> > >
> >
> > list(enumerate(some_list)) will give you a sequence, if that's what you 
> > want.
>
> Right.  And reversed(list(enumerate(some_list)) also works.  The point
> is that if you return sequence views (as Andrew mentioned), you don't
> need to cast to list explicitly, and you don't pay the computational
> cost of that either.
>

With enumerate, you might be able to make a lazy sequence, but then
people will ask for map to be able to return a sequence too - and
that's going to definitely run into problems. It's much safer to be
explicit about it: if you want a list, ask for a list.

In the rare instances where you actually need an enumerated lazy list
(ie where the cost of an eager list is too high AND it needs to be
enumerated), it's not that hard to whip up a thing that gives back the
index as well:

class Enumerated:
    def __init__(self, basis): self.basis = basis
    def __getitem__(self, idx): return (idx, self.basis[idx])
    def __len__(self): return len(self.basis)

That ought to do most or all of what you want. It's iterable and
reversible, and you can index it directly.

ChrisA
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/MFGKM6KBG3T4KMJCDRCWQMBFDB4D7OEC/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to