itertools.islice, itertools.chain
itertools.islice(iterable, stop)
itertools.islice(iterable, start, stop, step=1)
itertools.chain(*iterables)
itertools.chain.from_iterable(iterable)Build a new iterator from another iterable, or from several iterables in sequence. The input is consumed as you iterate, and is not reset afterward.
| Parameter | Description |
|---|---|
iterable / iterables | The source of values. islice and chain do not require a list; any iterable is accepted. |
start, stop, step | Positions as in sequence slicing. start defaults to 0 and step defaults to 1. None for stop means "until the input is exhausted". |
Returns: An iterator, not a list. Wrap the result in list() only when you need a reusable sequence.
- After list(it), a second list(it) is empty. That is normal iterator behavior, not a bug in itertools.
- islice(range(10), 2, 8, 2) yields 2, 4, 6. It does not include the stop index.
from itertools import chain, islice
it = iter([1, 2, 3])
print(list(it))
print(list(it))
print(list(islice(range(10), 2, 8, 2)))
print(list(chain([1, 2], [3], "ab")))
print(list(chain.from_iterable([[1, 2], [3]])))Expected output
[1, 2, 3]
[]
[2, 4, 6]
[1, 2, 3, 'a', 'b']
[1, 2, 3]