10.12. Iterator ISlice
Lazy evaluated
itertools.islice(iterable, stop)
itertools.islice(iterable, start, stop[, step])
Make an iterator that returns selected elements from the iterable. Works like sequence slicing but does not support negative values for start, stop, or step.
If start is zero or None, iteration starts at zero. Otherwise, elements from the iterable are skipped until start is reached.
If stop is None, iteration continues until the input is exhausted, if at all. Otherwise, it stops at the specified position.
If step is None, the step defaults to one. Elements are returned consecutively unless step is set higher than one which results in items being skipped.
>>> from itertools import islice
>>>
>>> IRIS = [
... ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'),
... (5.8, 2.7, 5.1, 1.9, 'virginica'),
... (5.1, 3.5, 1.4, 0.2, 'setosa'),
... (5.7, 2.8, 4.1, 1.3, 'versicolor'),
... (6.3, 2.9, 5.6, 1.8, 'virginica'),
... (6.4, 3.2, 4.5, 1.5, 'versicolor'),
... (4.7, 3.2, 1.3, 0.2, 'setosa'),
... (7.0, 3.2, 4.7, 1.4, 'versicolor'),
... (7.6, 3.0, 6.6, 2.1, 'virginica'),
... (4.6, 3.1, 1.5, 0.2, 'setosa'),
... ]
>>>
>>> rows = islice(IRIS, 1, None)
>>>
>>> for row in rows:
... print(row)
...
(5.8, 2.7, 5.1, 1.9, 'virginica')
(5.1, 3.5, 1.4, 0.2, 'setosa')
(5.7, 2.8, 4.1, 1.3, 'versicolor')
(6.3, 2.9, 5.6, 1.8, 'virginica')
(6.4, 3.2, 4.5, 1.5, 'versicolor')
(4.7, 3.2, 1.3, 0.2, 'setosa')
(7.0, 3.2, 4.7, 1.4, 'versicolor')
(7.6, 3.0, 6.6, 2.1, 'virginica')
(4.6, 3.1, 1.5, 0.2, 'setosa')
10.12.1. Use Case - 1
>>> from itertools import islice
>>>
>>>
>>> data = islice('ABCDEFG', 2, 6, 2 )
>>>
>>> next(data)
'C'
>>> next(data)
'E'
>>> next(data)
Traceback (most recent call last):
StopIteration