Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

itertools.islice

Lazily selects positions from an iterable using nonnegative bounds.

Version: Python 3.14; repository image, production runtime not attested

Syntax

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

Lazily selects positions from an iterable using nonnegative bounds.

The stop bound is excluded. Equal start and stop select nothing even if the iterator has more elements.

Use stop alone for a prefix, or start, exclusive stop and optional positive step. Numeric bounds must be nonnegative; None can leave stop open. Starting at index 2 and stopping before 8 with step 2 gives 2, 4, 6. Equal start and stop produce no results.

import itertools as I
it = iter(range(10))
assert list(I.islice(it, 2, 8, 2)) == [2, 4, 6]
assert next(it) == 8 and list(I.islice("abc", 2)) == ["a", "b"]

Examples

import itertools as I
print(list(I.islice(I.count(), 2, 8, 2)))
print(list(I.islice(range(3), 3, 3)))

Result

[2, 4, 6]
[]

Use stop alone for a prefix, or start, exclusive stop and optional positive step. Numeric bounds must be nonnegative; None can leave stop open. Starting at index 2 and stopping before 8 with step 2 gives 2, 4, 6. Equal start and stop produce no results.

Sources