Sub topic 4
Taking slices of any iterator with islice
What you need to know first
This chapter assumes you are comfortable with Python loops, lists and tuples, and the key= argument of sorted. You should also know the difference between an iterable and an iterator, and that an iterator is used up after one full pass. Earlier chapters covered count, cycle and repeat. Those produce streams that never end, so you need a safe way to take a bounded piece of them. That tool is islice.
Why list slicing does not work on iterators
A list supports slicing with items[2:5]. Slicing needs two things: a known length and random access by position. An iterator has neither. It hands out one item at a time and may never stop.
from itertools import count
stream = count(10, 5)
try:
print(stream[0:4])
except TypeError as error:
print(error)This prints 'itertools.count' object is not subscriptable. Converting the stream to a list first is not an option here, because list(count(10, 5)) would run until memory is exhausted.
itertools.islice gives you slice-like behavior on any iterable. It returns a new lazy iterator. No work happens until you pull items from it.
The three call forms
islice mirrors the range function's arguments:
from itertools import islice
islice(iterable, stop)
islice(iterable, start, stop)
islice(iterable, start, stop, step)Here is each form on a small string:
from itertools import islice
letters = "ABCDEFG"
print(list(islice(letters, 3)))
print(list(islice(letters, 2, 5)))
print(list(islice(letters, 1, 7, 2)))
print(list(islice(letters, 2, None)))
print(list(islice(letters, 0, None, 3)))The output is:
['A', 'B', 'C']
['C', 'D', 'E']
['B', 'D', 'F']
['C', 'D', 'E', 'F', 'G']
['A', 'D', 'G']Passing None for stop means "run to the end of the input". Passing None for start means "begin at the first item". step defaults to 1.
The simplest bounded use of an infinite stream looks like this:
from itertools import count, islice
print(list(islice(count(10, 5), 4)))This prints [10, 15, 20, 25]. The count iterator is infinite, but islice stops pulling after four items, so the program finishes.
Restrictions that differ from list slicing
islice copies the syntax of slicing but not all of its features.
| Feature | List slice | `islice` |
|---|---|---|
| Negative `start`, `stop` or `step` | Allowed | `ValueError` |
| Step of 0 | `ValueError` | `ValueError` |
| Works on iterators | No | Yes |
| Returns | New list | Lazy iterator |
| Can be indexed or measured with `len` | Yes | No |
Negative indices are rejected because counting from the end requires knowing where the end is. An iterator cannot tell you that without being fully consumed.
from itertools import islice
try:
list(islice("ABCDE", -2, None))
except ValueError as error:
print(error)The message says that the indices for islice() must be None or an integer in the range 0 to sys.maxsize. If you need the last few items of a stream, use collections.deque(iterator, maxlen=n), which keeps only the final n items as it consumes the input.
from collections import deque
print(list(deque(iter(range(1000)), maxlen=3)))This prints [997, 998, 999] and holds three items in memory at a time.
How islice consumes its input
islice does not jump to the start position. It has no way to. Instead it reads and discards every item before start. The cost of islice(it, 1_000_000, 1_000_005) is about a million steps, even though you receive only five items. For a list, items[1_000_000:1_000_005] is much cheaper because the list can jump straight there. If your data is already in a sequence, use normal slicing.
The second consequence is that islice shares state with the iterator you give it. It advances the underlying iterator, and that progress cannot be undone.
from itertools import islice
source = iter(range(10))
first = list(islice(source, 3))
second = list(islice(source, 3))
print(first)
print(second)
print(next(source))The output is:
[0, 1, 2]
[3, 4, 5]
6Each call continues where the previous one stopped. This makes islice a convenient way to take items in chunks from one iterator. It also makes a second subtle point: islice stops after the last item it yields, and reads no further than that point. Here the stop bound of 3 means exactly three items are pulled from source, so the next call picks up cleanly at 3.
There is one edge case. When you give a start, islice must read through item stop - 1, but it does not read item stop. So the underlying iterator is left positioned just after the last item you asked for. Compare this with a loop that tests a condition, such as takewhile, which has to consume the first failing item in order to know it fails.
from itertools import islice, takewhile
a = iter([1, 2, 3, 10, 4, 5])
print(list(takewhile(lambda x: x < 5, a)))
print(list(a))
b = iter([1, 2, 3, 10, 4, 5])
print(list(islice(b, 3)))
print(list(b))The output is:
[1, 2, 3]
[4, 5]
[1, 2, 3]
[10, 4, 5]takewhile swallowed the 10 that ended its run. islice left it in place. When you need to resume reading from an iterator, islice with a count is the predictable choice.
Laziness means nothing runs until you ask
Creating an islice object does no reading. The reading happens as you iterate.
from itertools import islice
def noisy():
for n in range(5):
print("producing", n)
yield n
pieces = islice(noisy(), 2)
print("created the slice")
for value in pieces:
print("got", value)The output is:
created the slice
producing 0
got 0
producing 1
got 1The generator is asked for two items and no more. Item 2 is never produced. This is what lets islice bound a generator that does expensive work, such as reading lines from a large file or calling an API page by page.
Common uses
Take the first n items
from itertools import islice
def first_n(iterable, n):
return list(islice(iterable, n))
with open(__file__) as handle:
print(first_n(handle, 3))This reads three lines from a file and stops. The rest of the file is never read from disk.
Skip a header
Pass start and None as the stop value to drop leading items:
from itertools import islice
lines = iter(["name,age", "Ada,36", "Linus,55"])
for row in islice(lines, 1, None):
print(row)This prints the two data rows and skips the header line.
Take every nth item
from itertools import islice, count
print(list(islice(count(), 0, 20, 5)))This prints [0, 5, 10, 15]. Note that islice still pulls all the skipped items from count(). Only the yielded items are returned.
Build a fixed-size chunk reader
Because repeated islice calls continue from the same iterator, you can read chunks in a loop:
from itertools import islice
def chunks(iterable, size):
iterator = iter(iterable)
while True:
chunk = list(islice(iterator, size))
if not chunk:
return
yield chunk
print(list(chunks(range(7), 3)))This prints [[0, 1, 2], [3, 4, 5], [6]]. Calling iter(iterable) first matters. If you passed a list directly to islice each time, every call would start again at the beginning and the loop would never end. Python 3.12 added itertools.batched for exactly this job, and a later chapter covers it.
Edge cases and gotchas
stopsmaller than or equal tostartgives an empty result.list(islice("ABC", 2, 1))is[].- A short input is not an error.
list(islice("AB", 10))is['A', 'B']. You get whatever exists. - Non-integer arguments such as floats raise
ValueError. Convert withint()first. isliceon a list restarts every time. A list is an iterable, not an iterator, so eachislice(my_list, 3)creates a fresh iterator from the beginning. Only an explicit iterator carries progress between calls.
from itertools import islice
data = [1, 2, 3, 4, 5, 6]
print(list(islice(data, 2)))
print(list(islice(data, 2)))
it = iter(data)
print(list(islice(it, 2)))
print(list(islice(it, 2)))The output is:
[1, 2]
[1, 2]
[1, 2]
[3, 4]- Reusing an
isliceobject does not work. Like every iterator, it is exhausted after one pass, and a secondlist()call returns[].
How the pieces fit together
Choosing between islice and other tools
- Use plain slicing
items[a:b]when the data is already a list, tuple or string and you want a real sequence back. - Use
islicewhen the input is an iterator, a generator, a file, or an infinite stream, or when you want to avoid building a copy. - Use
takewhilewhen the end of the piece depends on a condition and not a count. - Use
deque(..., maxlen=n)for the lastnitems. - Use
next(iterator, default)when you want exactly one item.
Exercise
A generator g = iter(range(100)) is read with a = list(islice(g, 5)) and then b = list(islice(g, 2, 4)). What are a and b, and what does next(g) return afterwards?
Show answer
a is [0, 1, 2, 3, 4]. The second call continues from 5, discards 5 and 6, and yields 7 and 8, so b is [7, 8]. It reads no further than the item before stop, so next(g) returns 9.
Exercise
Write a function every_other_after_header(lines) that takes an iterator of text lines, skips the first line, and returns a list of every second line after that, beginning with the first data line. Do not call list on the whole input before slicing.
Show answer
Use a start of 1 and a step of 2: def every_other_after_header(lines): return list(islice(lines, 1, None, 2)). For input ["h", "a", "b", "c", "d"] it returns ["a", "c"].