itertools.islice and slice objects

S

Steven Bethard

Is there a reason that itertools.islice doesn't support None arguments
for start and step? This would be handy for use with slice objects:
>>> r = range(20)
>>> s1 = slice(2, 10, 2)
>>> s2 = slice(2, 10)
>>> s3 = slice(10)
>>> list(itertools.islice(r, s1.start, s1.stop, s1.step)) [2, 4, 6, 8]
>>> list(itertools.islice(r, s2.start, s2.stop, s2.step))
Traceback (most recent call last):
File said:
>>> list(itertools.islice(r, s2.start, s2.stop, s2.step or 1)) [2, 3, 4, 5, 6, 7, 8, 9]
>>> list(itertools.islice(r, s3.start, s3.stop, s3.step))
Traceback (most recent call last):
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Of course, I can get (start, stop, step) tuples with slice.indices, but
only if I know the length of the iterable, which kinda defeats the
purpose of using itertools...
>>> list(itertools.islice(r, *s2.indices(10))) [2, 3, 4, 5, 6, 7, 8, 9]
>>> list(itertools.islice(r, *s3.indices(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Steve
 
R

Raymond Hettinger

[Steven Bethard]
Is there a reason that itertools.islice doesn't support None arguments
for start and step? This would be handy for use with slice objects

Offhand, this seems like a reasonable idea. Please file a Py2.5 feature request
and assign to me.

Of course, I can get (start, stop, step) tuples with slice.indices, but
only if I know the length of the iterable, which kinda defeats the
purpose of using itertools...

The main purpose is to extract elements one at time instead of all at once.
This memory friendly approach results in better scalability.


Raymond Hettinger
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top