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 itertools module 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, and step parameters.
  • When the start parameter is greater than zero, the elements from the iterable are skipped until start is reached.
  • The default value of step is 1.
  • If 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.
  • If a single value is passed along with the iterable, the value acts as the stop parameter.

Code example

from itertools import islice
def 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 = 4
islice_with_single_value(iterator, val)
start = 5
stop = 10
islice_with_start_stop(iterator, start, stop)
step = 3
islice_with_start_stop_step(iterator, start, stop, step)

Explanation

  • Line 1: We import the islice function.
  • Lines 3–4: We define the 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.
  • Lines 6–7: We define the islice_with_start_stop method that uses the islice function with the given iterable, start, and stop values.
  • Lines 9–10: We define the islice_with_start_stop_step method that uses the islice function with the given iterable, start, stop, and step values.
  • Line 13: We define the iterable as iterator.
  • Line 14: We define val.
  • Line 15: We invoke islice_with_single_value with iterator and val. The elements from 0 to val-1 are returned.
  • Line 17: We define start.
  • Line 18: We define stop.
  • Line 19: We invoke islice_with_start_stop with iterator, start and stop. The elements from start to stop-1 are returned.
  • Line 21: We define step.
  • Line 22: We invoke 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.

Free Resources