[Python-ideas] Consider making enumerate a sequence if its argument is a sequence

Andrew Barnert abarnert at yahoo.com
Wed Sep 30 21:42:05 CEST 2015

On Sep 30, 2015, at 12:25, Random832 <random832 at fastmail.com> wrote:
>> On Wed, Sep 30, 2015, at 13:19, Neil Girdhar wrote:
>> I guess, I'm just asking for enumerate to go through the same change that
>> range went through.  Why wasn't it a problem for range?
> Range has always returned a sequence.
> Anyway, why stop there? Why not have map return a sequence?

Even when it's called with a set, or an iterator? Yes, you _could_ do that by lazily adding values to a list as needed, but that could lead to some confusing behavior. For example, len(m) or m[-1] has to evaluate the rest of the input, which could take infinite time (well, it'll run out of memory first…).

> Zip?
> Anything that is a 1:1 mapping (or 1+1:1 in zip's case) could in
> principle be changed to return a sequence when given one. Who decides
> what does and doesn't benefit from random access?

The end user, of course. Some applications will never pass an infinite, or even very long, iterable into map, so they'd want random access and size and reversibility. Others won't ever want those features, but would want to pass in infinite iterators. That's why I think the best answer is to let people write (or install from PyPI) LazyList classes that fit their use cases, instead of trying to come up with one that tries to do everything and is misleading as often as it's useful.

It's not actually impossible to design something that does a lot more without being inconsistent or confusing, but it's a bigger change than it appears at first glance, and would add a lot more complexity to the language than I think is worth it for the benefits. Again, see http://stupidpythonideas.blogspot.com/2014/07/swift-style-map-and-filter-views.html for details.

> Or sliceability. It wouldn't be hard, in principle, to write a
> general-purpose function for slicing an iterator (i.e. returning an
> iterator that yields the elements that slicing a list of the same length
> would have given), particularly if it's limited to positive values.

You mean itertools.islice?

More information about the Python-ideas mailing list