itertools.islice and slice objects
Steven Bethard
steven.bethard at gmail.com
Tue Nov 23 14:00:30 EST 2004
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 "<interactive input>", line 1, in ?
TypeError: an integer is required
>>> 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):
File "<interactive input>", line 1, in ?
TypeError: an integer is required
>>> list(itertools.islice(r, s3.start or 0, s3.stop, s3.step or 1))
[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
More information about the Python-list
mailing list