On this page
itertools.islice
Prev: itertools.groupby | Up: itertools | Next: itertools.pairwise
Rel: itertools.accumulate, itertools.batched, itertools.chain, itertools.combinations
Ref: docs.python.org — itertools.islice
Tags: #public #python3 #stdlib #itertools
Import
import itertools
from itertools import islice
Signature & Overview
itertools.islice(iterable, stop) --> islice object
islice(iterable, start, stop[, step]) --> islice object Return an iterator whose next() method returns selected values from an iterable. If start is specified, will skip all preceding elements;
Usage
from itertools import islice
gen = (x * x for x in range(100))
assert list(islice(gen, 2, 8, 2)) == [4, 16, 36]
Gotchas
- No negative indices or steps:
islice(it, -5)raisesValueError; usecollections.deque(it, maxlen=5)to grab the last 5 items of an iterator. - Consumes skipped elements:
islice(gen, 5, 10)advancesgenpast the first 5 items permanently.
REPL Inspect
from itertools import islice
help(islice)
Linked from
Related notes
- tuts/python3/stdlib_module/itertools/groupby Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/pairwise Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/accumulate Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/batched Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/chain Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations_with_replacement shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/compress shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/count shared tags: #itertools, #stdlib