Python itertools.islice() Function



The Python itertools.islice() function is used to return selected elements from an iterable. Unlike regular slicing, it works with iterators and does not require materializing the entire sequence in memory.

This function is useful when working with large datasets or infinite iterators. By specifying a start, stop, and step, we can extract a portion of an iterable efficiently.

Syntax

Following is the syntax of the Python itertools.islice() function −

itertools.islice(iterable, start, stop[, step])

Parameters

This function accepts the following parameters −

  • iterable: The input iterable from which elements will be extracted.
  • start: The index at which extraction begins.
  • stop: The index at which extraction ends.
  • step (optional): The step size for skipping elements (default is 1).

Return Value

This function returns an iterator that yields elements based on the given slicing parameters.

Example 1

Following is an example of the Python itertools.islice() function. Here, we extract the first five elements from a range −

Open Compiler
import itertools numbers = range(10) selected = itertools.islice(numbers, 5) for num in selected: print(num)

Following is the output of the above code −

0
1
2
3
4

Example 2

Here, we extract a portion of a list starting from index 2 and stopping at index 6 using the itertools.islice() function −

Open Compiler
import itertools letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] selected = itertools.islice(letters, 2, 6) for letter in selected: print(letter)

Output of the above code is as follows −

c
d
e
f

Example 3

Now, we use itertools.islice() function with a step parameter to skip elements −

Open Compiler
import itertools numbers = range(20) selected = itertools.islice(numbers, 2, 15, 3) for num in selected: print(num)

The result obtained is as shown below −

2
5
8
11
14

Example 4

We can use itertools.islice() function with an infinite iterator to control its output. Here, we use it with itertools.count() function to limit the output −

Open Compiler
import itertools counter = itertools.count(10, 2) selected = itertools.islice(counter, 5) for num in selected: print(num)

The result produced is as follows −

10
12
14
16
18
python_modules.htm
Advertisements