islice Windows Iterators Without Copies
Slice iterators lazily with islice: consecutive batches continue where the last slice stopped, while windows over a list leave the sequence untouched.
Code
from itertools import islice
def events():
for n in range(1, 9):
yield f'event-{n}'
stream = events()
# islice 惰性切片有状态:每次消费后位置向前走,接着取就是下一批
print('batch 1:', list(islice(stream, 3)))
print('batch 2:', list(islice(stream, 3)))
print('batch 3:', list(islice(stream, 3))) # 只剩 2 条,不足不补
# 对序列切片则是纯窗口 (window):不复制、不改动原列表
page = list(range(10, 20))
print('window :', list(islice(page, 2, 6)))
print('list ok:', page[0] == 10)
# start/stop/step 全支持,负值不行:islice 只能向前消费迭代器
print('stepped:', list(islice(page, 0, 10, 3)))Output
Captured from a sandboxed run of this snippet in the build pipeline.
batch 1: ['event-1', 'event-2', 'event-3']
batch 2: ['event-4', 'event-5', 'event-6']
batch 3: ['event-7', 'event-8']
window : [12, 13, 14, 15]
list ok: True
stepped: [10, 13, 16, 19]How it works
Count the function events as the entire surface area of islice Windows Iterators Without Copies.
Repetition is confined to for n in range(1, 9) — the rest of the file is straight-line.
Applying it
Entry signature: def events()
The demo output is labeled (batch 1:, batch 2:, batch 3:), so every printed line maps back to its originating operation.
Import events from the file and call it — the rest of the code is implementation detail.
Statements that matter
def events():
for n in range(1, 9):
yield f'event-{n}'
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `events` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.