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])- [ ]optional part
- iterable
- An iterable.Iterable
- start
- The position of the first item, 0 by default.int | NoneOptional
- stop
- The position before which the selection stops; None means to the end.int | None
- step
- The step, 1 by default.int | NoneOptional
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.
