Understand Python itertools.islice() with Examples – Python Tutorial

By | October 9, 2022

Python itertools.islice() function can allow us to get a part of an iterable object. In this tutorial, we will use some examples to show you how to do.

Syntax

itertools.islice() is defined as:

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

It will return selected elements from the iterable. It will return a itertools.islice object.

We should notice:

  • start = 0 if start is None.
  • start = 0 if start < 0

How to use itertools.islice()?

Here is a simple example:

# islice('ABCDEFG', 2) --> A B
# islice('ABCDEFG', 2, 4) --> C D
# islice('ABCDEFG', 2, None) --> C D E F G
# islice('ABCDEFG', 0, None, 2) --> A C E G

We should notice, we can not set value for start or stop parameter.

For example:

from itertools import islice

s = 'ABCDEFG'

y = islice(s, start = 1, stop = 3)
print(y)
for x in y:
    print(x)

Run this code, we will get an error: TypeError: islice() does not take keyword arguments

The correct way is:

y = islice(s, 1, 3)
print(y)
for x in y:
    print(x)

Then we can find:

y is <itertools.islice object at 0x000001C5131F6D68>

and x is: B C

Leave a Reply