Python Glossary Русский

all Python 3Iterators & generatorsterm

itertools.islice

itertools

Slices an iterator without materializing it. The counterpart of a slice for iterables.

Syntax

from itertools import islice
islice(iterable, stop)
islice(iterable, start, stop[, step])

islice never looks backwards: negative start, stop and step are rejected, and the step must be positive. It also genuinely consumes the source — items before start are read and thrown away, and afterwards the underlying iterator sits wherever the slice stopped, so a second islice continues from there instead of starting over.

Examples

from itertools import islice
print(list(islice(range(100), 5)))  # → [0,1,2,3,4]
print(list(islice(range(100), 2, 7)))  # → [2,3,4,5,6]
print(list(islice(range(100), 0, 10, 2)))  # → [0,2,4,6,8]
from itertools import islice
# islice с бесконечным генератором
def naturals():
    n = 0
    while True:
        yield n
        n += 1
print(list(islice(naturals(), 5, 10)))  # → [5, 6, 7, 8, 9]
# Пагинация: страница 3 по 10
print(list(islice(range(100), 20, 30)))  # → [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
# Каждый третий элемент
print(list(islice(range(20), 0, None, 3)))  # → [0, 3, 6, 9, 12, 15, 18]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy