Limit Consumption with islice and takewhile
Core idea
islice(source, stop) selects a prefix; islice(source, start, stop, step) selects positions with a nonnegative start and stop (or None), and a positive step (or None for one). takewhile(predicate, source) selects a consecutive prefix that passes a condition, unlike filter which continues searching. Both consume a source iterator.
from itertools import count, isliceprint(list(islice(count(40), 3)))A finite stop bounds an infinite source.
Observe skipped positions
from itertools import islicesource = iter([10, 20, 30, 40, 50, 60])print(list(islice(source, 1, 4, 2)))print(next(source))Fully consuming the slice advances the source through index 3, including skipped items.
Stop at an invalid reading
from itertools import takewhilesource = iter([8, 6, -1, 4])print(list(takewhile(lambda n: n >= 0, source)))print(next(source))The failing -1 is consumed and omitted; the remaining 4 is still available.
Common mistake
islice is not a random-access slice and cannot use negative indices or a negative step. takewhile does not preserve the first failing item.
Practice
Use islice to preview two values from count(7). Then predict both outputs if the final example starts with -1.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Bound iterator consumption
Check your understanding of islice and takewhile.
What is printed?
from itertools import count, isliceprint(list(islice(count(9), 2)))What is printed?
from itertools import takewhiles = iter([1, 0, 4])print(list(takewhile(bool, s)))print(next(s))What happens?
from itertools import islicelist(islice([1, 2, 3], -2, None))What is the key difference between takewhile and filter?