The itertools module in the standard library provides a number of useful functions for iterating through iterables efficiently.
The
islice()
function in the module allows slicing in iterables, unlike in normal slicing say using the builtin slice()
function, the sliced elements are not stored in memory all at once. Instead the requested elements are produced on demand. The function is also more flexible as it can as well be used with non-sequence iterables such as sets and dictionaries.
Its syntax is similar to that of the builtin slice()
function.
islice(iterable, stop)
islice(iterable, start, stop, step = 1)
iterable |
The iterable object to be iterated over. |
start |
The index at which the slicing will begin. |
stop |
The index at which the slicing will end (exclusive). |
step |
The size of the "jump" the function takes between the values in the sequence |
The function returns an iterator that yields elements from the iterables whose indices from the start
to stop
(exclusive) with the step
parameter as the 'jump' value.
from itertools import islice
data = range(10)
#get the first 5 elements
for i in islice(data, 5):
print(i)
As in above case, when only a single integer argument is given to the islice()
function alongside the iterable, the integer is used as the stop
value, the slicing begins from the first element(index 0) up to the stop
vlaue.
from itertools import islice
data = range(20)
for i in islice(data, 0, 15, 2):
print(i)
When all the four parameters are given, the second parameter becomes the start
, the third becomes stop
, and the last one becomes the step
.