What is itertools.islice() method in Python?
Overview
The islice() method in the itertools module in Python gets selected elements from iterators based on the index of the elements.
This functionality is very similar to slicing in Python.
Note: The
itertoolsmodule in Python provides functions that help us iterate through iterables.
Syntax
itertools.islice(iterable, start, stop, step)
Parameters
iterable: This is the iterable for which iterators need to be returned.start: This is the starting point of the iteration.stop: This is the ending point of the iteration.step: This is the number of elements to skip during the iteration.
Important points
- This method doesn’t support negative values for
start,stop, andstepparameters. - When the
startparameter is greater than zero, the elements from the iterable are skipped untilstartis reached. - The default value of
stepis1. - If
stopis a positive value, the iteration stops at the positive value. If it’sNone, the iteration does not stop until the iterator is exhausted. - If a single value is passed along with the iterable, the value acts as the
stopparameter.
Code example
from itertools import islicedef islice_with_single_value(iterator, val):print("islice(%s, %s) = %s" % (iterator, val, list(islice(iterator, val))))def islice_with_start_stop(iterator, start, stop):print("islice(%s, %s, %s) = %s" % (iterator, start, stop, list(islice(iterator, start, stop))))def islice_with_start_stop_step(iterator, start, stop, step):print("islice(%s, %s, %s, %s) = %s" % (iterator, start, stop, step, list(islice(iterator, start, stop, step))))iterator = range(10)val = 4islice_with_single_value(iterator, val)start = 5stop = 10islice_with_start_stop(iterator, start, stop)step = 3islice_with_start_stop_step(iterator, start, stop, step)
Explanation
- Line 1: We import the
islicefunction. - Lines 3–4: We define the
islice_with_single_valuemethod that uses theislicefunction with the given iterable and the single value. The single value here acts as thestopparameter. - Lines 6–7: We define the
islice_with_start_stopmethod that uses theislicefunction with the giveniterable,start, andstopvalues. - Lines 9–10: We define the
islice_with_start_stop_stepmethod that uses theislicefunction with the giveniterable,start,stop, andstepvalues. - Line 13: We define the iterable as
iterator. - Line 14: We define
val. - Line 15: We invoke
islice_with_single_valuewithiteratorandval. The elements from0toval-1are returned. - Line 17: We define
start. - Line 18: We define
stop. - Line 19: We invoke
islice_with_start_stopwithiterator,startandstop. The elements fromstarttostop-1are returned. - Line 21: We define
step. - Line 22: We invoke
islice_with_start_stop_stepwithiterator,start,stop, andstep. The elements fromstarttostop-1are returned, where everystepnumber of elements are skipped.