Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question

Write a generator that yields an input sequence in fixed-size chunks without building all chunks up front.

Answer

For a sequence that supports slicing, iterate start indexes in steps of the chunk size and `yield` one slice at a time. Because the function yields instead of returning a complete list of slices, callers can consume each chunk incrementally. Validate that the chunk size is positive so invalid input fails explicitly instead of producing confusing behavior.

Strong answer includes

  • uses yield to produce chunks lazily
  • advances indexes by the chunk size
  • validates a positive chunk size

Practical example

Lazy sequence chunker
Python
editable · browser sandbox
Result
Run the code to see the result.

The generator holds only its current execution state; each slice is created when the caller asks for the next chunk.

Expected result: [[1, 2], [3, 4], [5]]

#generators#yield#algorithms

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semanticsThe Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basics