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.
itertools.islice(iterable, start, stop, step)
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.start, stop, and step parameters.start parameter is greater than zero, the elements from the iterable are skipped until start is reached.step is 1.stop is a positive value, the iteration stops at the positive value. If it’s None, the iteration does not stop until the iterator is exhausted.stop parameter.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)
islice function.islice_with_single_value method that uses the islice function with the given iterable and the single value. The single value here acts as the stop parameter.islice_with_start_stop method that uses the islice function with the given iterable, start, and stop values.islice_with_start_stop_step method that uses the islice function with the given iterable, start, stop, and step values.iterator.val.islice_with_single_value with iterator and val. The elements from 0 to val-1 are returned.start.stop.islice_with_start_stop with iterator, start and stop. The elements from start to stop-1 are returned.step.islice_with_start_stop_step with iterator, start, stop, and step. The elements from start to stop-1 are returned, where every step number of elements are skipped.