Python Function Reference

itertools.islice

Take part of the items of an iterator, like a slice.

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

Parameters

iterableIterable
An iterable.
startint | Noneoptional
The position of the first item, 0 by default.
stopint | None
The position before which the selection stops; None means to the end.
stepint | Noneoptional
The step, 1 by default.

Return value

An iterator over the selected items.

Examples

The first three items

Python 3.13
from itertools import islice

print(list(islice('abcdefg', 3)))
['a', 'b', 'c']

A slice with a start and a step

Python 3.13
from itertools import islice

print(list(islice(range(10), 2, 8, 2)))
[2, 4, 6]

Details

It works like a slice but for any iterator, including infinite ones and files. Negative values are not supported and raise ValueError. Skipped items of the iterator are consumed and do not come back.

See also