Complete worked example
python
from itertools import islice
def inspect_example(values, count):
if type(count) is not int or count < 0:
raise ValueError('count must be a nonnegative integer')
seen = []
def transformed():
for value in values:
seen.append(value)
yield value * 2
stream = transformed()
selected = list(islice(stream, count))
return {'selected': selected, 'consumed': seen}- Reasoning
- Calling transformed constructs a generator without executing its loop. Passing that stream to islice and then materializing the slice requests only the chosen number of values. With four inputs and count two, selected contains two doubled values and consumed contains the first two original inputs.