Split a List Into Fixed-Size Chunks

Medium ⏱ 12 min 51% acceptance ★★★★☆ 4.4
Write chunk_list(items, size) that splits items into consecutive sublists of length size. The final chunk may be shorter if len(items) is not a multiple of size. Assume size is a positive integer.

Examples

Example 1
Input
items = [1, 2, 3, 4, 5, 6, 7], size = 3
Output
[[1, 2, 3], [4, 5, 6], [7]]
Explanation

Groups of 3, with a shorter final group.

Constraints

  • size >= 1
  • 0 <= len(items) <= 10^5

Topics

ListsSlicing

Companies

AmazonSwiggy

Hints

Hint 1

Step through indices 0, size, 2*size, ... and slice items[i:i+size] each time.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.