Sub topic 4
Taking slices of any iterator with islice
This chapter assumes you know Python loops and comprehensions, basic list and tuple slicing, and what an iterator is (an object you advance with next() that is used up after one pass). Generators help but are not required.
Why list slicing does not work on iterators
The slice syntax seq[a:b] needs indexing and a known length. Iterators have neither, so slicing one fails.
from itertools import count
stream = count(10, 5)
try:
stream[:4]
except TypeError as error:
print(error)itertools.islice solves this. It gives you a slice of any iterable as a new lazy iterator. It never builds the whole sequence, so it also works on infinite streams.
The three call forms
islice mirrors the arguments of range:
islice(iterable, stop)islice(iterable, start, stop)islice(iterable, start, stop, step)
Passing None for stop means "run to the end". Negative values are not allowed for start, stop or step, because an iterator cannot look backward or know where it ends.
from itertools import count, islice
print(list(islice(count(10, 5), 4)))
print(list(islice('ABCDEFG', 2, 5)))
print(list(islice('ABCDEFG', 0, None, 3)))The output is:
[10, 15, 20, 25]
['C', 'D', 'E']
['A', 'D', 'G']The first line bounds an infinite counter. The other two show start/stop and step on a finite string.
How islice works internally
islice advances the source one item at a time and throws away items before start. It cannot jump ahead. Skipping to position 1,000,000 still reads and discards 1,000,000 items. The cost is proportional to how far you go, not to how many items you keep.
Because the diagram type below is the only one needed, here it is in the required form.
islice consumes the source
The slice shares the original iterator. Items that islice reads are gone from the source. This is the most common surprise.
from itertools import islice
it = iter(range(10))
print(list(islice(it, 3)))
print(list(islice(it, 3)))
print(next(it))The output is [0, 1, 2], then [3, 4, 5], then 6. Each call continues where the last one stopped. You can use this on purpose to read a stream in pieces.
One subtlety: when islice stops at stop, it has read exactly stop items from the source, not one more. This differs from takewhile, which must read one extra item to find the first failing value.
Common uses
Peek at the first lines of a large file without loading it:
from itertools import islice
import io
file = io.StringIO("one\ntwo\nthree\nfour\n")
for line in islice(file, 2):
print(line.rstrip())Take the first match from a generator, with a default if none exist:
from itertools import islice
squares = (n * n for n in range(1, 100))
first_big = next(islice((s for s in squares if s > 50), 1), None)
print(first_big)This prints 64. Reading lazily means the generator stops after the first hit.
Read a fixed-size header and then process the rest from the same iterator:
from itertools import islice
rows = iter(["id,name", "1,Ann", "2,Bo"])
header = list(islice(rows, 1))
print(header)
print(list(rows))This works because islice leaves the remaining items in rows.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `islice(it, -3)` | `ValueError` | Use a list, or `collections.deque(it, maxlen=3)` for the last items |
| `islice(it, 0, 5, 0)` | `ValueError`, step must be at least 1 | Use a positive step |
| Reusing a sliced iterator | Second pass is empty or shifted | Store the result with `list()` |
| Expecting `islice(it, 5)[2]` to work | `TypeError` | `islice` returns an iterator, so wrap it in `list()` first |
Exercise
Given it = iter(range(20)), what do list(islice(it, 2, 6, 2)) and then next(it) print?
Show answer
The first call prints [2, 4]. It reads items 0 to 5 from the source (start 2, stop 6, step 2 yields positions 2 and 4, and islice consumes up to the stop position). The next call to next(it) then returns 6.
Exercise
Write code that prints the first three even numbers from count(1) using islice and a generator expression.
Show answer
from itertools import count, islice print(list(islice((n for n in count(1) if n % 2 == 0), 3))) This prints [2, 4, 6].