[Python-ideas] Integrate some itertools into the Python syntax
Chris Angelico
rosuav at gmail.com
Mon Mar 28 12:22:56 EDT 2016
On Tue, Mar 29, 2016 at 3:13 AM, Chris Barker <chris.barker at noaa.gov> wrote:
> On Mon, Mar 28, 2016 at 8:04 AM, Chris Angelico <rosuav at gmail.com> wrote:
>
>>
>> >>> range(10, 100)[25:35]
>> range(35, 45)
>>
>> It's a slice. Whether it's random access or not is pretty much
>> unrelated to slicing; you get a slice of the underlying object,
>> whatever that is. A slice of a sliceable iterator should be a sliced
>> iterator.
>
>
> sure -- but that works great for range, because is is an lazy evaluated
> sequence, which of course makes it iterable, but I think the trick is:
>
>
> arbitrary_iterable[10:20]
>
> should return an iterable that will return the 10th to the 20th item when
> iterated -- doable, but:
>
> for i in arbitrary_iterable[10:20]:
> pass
>
> will then have to call the underlying iterable 20 times -- if it's an
> iterator that isn't a sequence, its state will have been altered.
>
> so I'm not sure how to go about this -- but it would be nice.
I don't think arbitrary iterables should be sliceable. Arbitrary
*iterators* can be, because that operation has well-defined semantics
(just tie in with itertools.islice); the state of the underlying
iterator *will* be changed.
> Also, arbitrary_iterable[-10:]
>
> would be essentially impossible.
I suppose it could be something like:
iter(collections.deque(arbitrary_iterable, maxlen=10))
but that's not what people will normally expect. Much better for
various iterable types to define their own slice handling.
ChrisA
More information about the Python-ideas
mailing list