Programming Search⌘K

Taskintro

Iterate in chunks

Also called split a list into chunks, batch a list, chunk a list, groups of n items, partition into fixed-size parts.

Split a list of integers into consecutive chunks of a fixed size, where the last chunk can be shorter.

Task

Split a list of integers into consecutive chunks of a fixed size. The function chunks(items, size) returns the chunks in order. Each chunk has size items, except the last chunk, which can be shorter. For example, chunks([1, 2, 3, 4, 5], 2) is [[1, 2], [3, 4], [5]].

The size is at least 1. The items are 32-bit signed integers, and the list can be empty. Then there are no chunks, so the result is an empty list, not a list with one empty chunk.

Solutions

Language Split into chunks of size items
Python itertools.batched, with a list of each chunk
JavaScript, TypeScript a loop with slice(i, i + size)
Java a loop with Arrays.copyOfRange
C# items.Chunk(size).ToArray()
Go slices.Collect(slices.Chunk(items, size))
Rust items.chunks(size), with a Vec of each chunk
C a loop that writes a pointer and a length for each chunk
C++ a loop with std::span::subspan
Bash a loop with ${items[*]:i:size}
  • The last chunk. batched gives tuples, and "The last batch may be shorter than n."1 For Chunk, "Each chunk except the last one will be of size size."2 The other solutions use the smaller of size and the number of items that are left.
  • The number of chunks. The C and Java solutions calculate the number of chunks as n / size plus 1 when n % size is not 0.
  • C. Each chunk is a pointer into the input and a length, so the function does not copy the items.
  • Bash. The function prints one line for each chunk, with the items separated by spaces.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: an empty list gives no chunks.
  • size-one: each chunk has 1 item.
  • size-larger: chunks([1, 2], 5) is [[1, 2]], one chunk with all the items.
  • size-equal: chunks([1, 2, 3], 3) is [[1, 2, 3]].
  • last-shorter: chunks([1, 2, 3, 4], 3) is [[1, 2, 3], [4]].
  • negative and extremes: negative items, -2147483648 and 2147483647 stay in their chunks.

Pitfalls

  • Python the zip idiom drops the last short chunk. zip(*[iter(s)]*n) repeats one iterator n times. "This has the effect of dividing the input into n-length chunks."3 But zip stops at the shortest input, so the last item 5 has no chunk. Use batched:
from itertools import batched

items = [1, 2, 3, 4, 5]
print(list(zip(*[iter(items)] * 2)))
print(list(batched(items, 2)))
Output
[(1, 2), (3, 4)]
[(1, 2), (3, 4), (5,)]
  • JavaScript splice empties the input. "The splice() method of Array instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in place."4 In the example, the chunks are correct, but items is empty after the loop. Use slice, which makes a copy:
const items = [1, 2, 3, 4, 5];
const out = [];
while (items.length > 0) {
  out.push(items.splice(0, 2));
}
console.log(out);
console.log(items);
Output
[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]
[]
  • Java subList is a view of the list. "The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa."5 In the example, chunk.set(0, 99) changes items. A new ArrayList of the sublist is a copy:
import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> items = new ArrayList<>(List.of(1, 2, 3, 4));
    List<Integer> chunk = items.subList(0, 2);
    chunk.set(0, 99);
    System.out.println(items);
    List<Integer> copy = new ArrayList<>(items.subList(2, 4));
    copy.set(0, 0);
    System.out.println(items);
  }
}
Output
[99, 2, 3, 4]
[99, 2, 3, 4]
  • C# Chunk throws for a size below 1. Chunk throws ArgumentOutOfRangeException when "size is below 1"2:
using System;
using System.Linq;

int[] items = { 1, 2, 3 };
Console.WriteLine(items.Chunk(2).Count());
try
{
    items.Chunk(0).ToArray();
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine(e.GetType().Name);
}
Output
2
ArgumentOutOfRangeException
  • Go an append to a chunk can change the next chunk. a[0:2] has the capacity of the rest of a, so append writes 99 into a[2]. For slices.Chunk, "All sub-slices are clipped to have no capacity beyond the length."6 Thus append makes a new array, and b does not change:
package main

import (
	"fmt"
	"slices"
)

func main() {
	a := []int{1, 2, 3, 4}
	c := a[0:2]
	c = append(c, 99)
	fmt.Println(a, c)

	b := []int{1, 2, 3, 4}
	for d := range slices.Chunk(b, 2) {
		d = append(d, 99)
		fmt.Println(b, d)
		break
	}
}
Output
[1 2 99 4] [1 2 99]
[1 2 3 4] [1 2 99]
  • Rust chunks_exact drops the last short chunk. With chunks_exact, "the last up to chunk_size-1 elements will be omitted and can be retrieved from the remainder function of the iterator"7. In the example, 5 is only in the remainder. Use chunks to keep the last short chunk:
fn main() {
    let items = [1, 2, 3, 4, 5];
    let exact = items.chunks_exact(2);
    println!("{:?}", exact.remainder());
    println!("{:?}", exact.collect::<Vec<_>>());
    println!("{:?}", items.chunks(2).collect::<Vec<_>>());
}
Output
[5]
[[1, 2], [3, 4]]
[[1, 2], [3, 4], [5]]
  • C (n + size - 1) / size can wrap around. "Unsigned integer arithmetic is always performed modulo"8 a power of 2. When n is SIZE_MAX, n + size - 1 wraps around, and the number of chunks is 0. n / size + (n % size != 0) has no overflow:
#include <stdint.h>
#include <stdio.h>

int main(void) {
    size_t n = SIZE_MAX;
    size_t size = 2;
    size_t wrong = (n + size - 1) / size;
    size_t right = n / size + (n % size != 0);
    printf("%zu %d\n", wrong, right == SIZE_MAX / 2 + 1);
    return 0;
}
Output
0 1
  • C++ subspan refers to the input, and its count must stay in the span. subspan "Obtains a subview over some consecutive elements of this span"9, so first[0] = 9 changes items[0]. For a count past the end, "If the implementation is not hardened, the behavior is undefined."9 Use the smaller of the size and the number of items that are left:
#include <algorithm>
#include <iostream>
#include <span>
#include <vector>

int main() {
    std::vector<int> items{1, 2, 3, 4, 5};
    std::span<int> all(items);
    auto first = all.subspan(0, 2);
    first[0] = 9;
    std::cout << items[0] << '\n';
    std::size_t i = 4;
    auto last = all.subspan(i, std::min<std::size_t>(2, all.size() - i));
    std::cout << last.size() << '\n';
}
Output
9
1
  • Bash ${items:0:2} is a part of the first item. "Referencing an array variable without a subscript is equivalent to referencing with a subscript of 0."10 Thus ${items:0:2} is the first 2 characters of 123. With @, "the result is the length members of the array beginning with ${parameter[offset]}"10:
#!/usr/bin/env bash
items=(123 456 789)
echo "${items:0:2}"
echo "${items[@]:0:2}"
Output
12
123 456

Code

The build runs the native tests of each language in a pinned toolchain.

chunks.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-in-chunks/.

from itertools import batched


def chunks(items: list[int], size: int) -> list[list[int]]:
    """Return the chunks of items with size items each; the last chunk can be shorter."""
    # batched gives tuples, so make a list of each chunk.
    return [list(b) for b in batched(items, size)]
test_chunks.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-in-chunks/.

import pytest

from chunks import chunks

CASES = {
    "pairs": ([1, 2, 3, 4, 5], 2, [[1, 2], [3, 4], [5]]),
    "triples": ([1, 2, 3, 4, 5, 6], 3, [[1, 2, 3], [4, 5, 6]]),
    "empty": ([], 3, []),
    "size-one": ([7, 8, 9], 1, [[7], [8], [9]]),
    "size-larger": ([1, 2], 5, [[1, 2]]),
    "size-equal": ([1, 2, 3], 3, [[1, 2, 3]]),
    "last-shorter": ([1, 2, 3, 4], 3, [[1, 2, 3], [4]]),
    "negative": ([-1, -2, -3], 2, [[-1, -2], [-3]]),
    "extremes": ([-2147483648, 2147483647, 0], 2, [[-2147483648, 2147483647], [0]]),
}


@pytest.mark.parametrize("name", CASES)
def test_chunks(name):
    items, size, want = CASES[name]
    assert chunks(items, size) == want
chunks.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

#include "chunks.hpp"

#include <algorithm>

std::vector<std::vector<int>> chunks(std::span<const int> items, std::size_t size) {
    std::vector<std::vector<int>> out;
    for (std::size_t i = 0; i < items.size(); i += std::min(size, items.size() - i)) {
        // The count must not go past the end of the span.
        auto c = items.subspan(i, std::min(size, items.size() - i));
        out.emplace_back(c.begin(), c.end());
    }
    return out;
}
chunks.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

#pragma once

#include <cstddef>
#include <span>
#include <vector>

// chunks returns the chunks of items with size items each; the last chunk can
// be shorter. size must be at least 1.
std::vector<std::vector<int>> chunks(std::span<const int> items, std::size_t size);
test_chunks.cpp 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

#include "chunks.hpp"

#include <cstddef>
#include <iostream>
#include <string_view>
#include <vector>

static int failures = 0;

using Chunks = std::vector<std::vector<int>>;

static void check(std::string_view name, const std::vector<int> &items, std::size_t size, const Chunks &want) {
    if (chunks(items, size) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("pairs", std::vector<int>{1, 2, 3, 4, 5}, 2, Chunks{{1, 2}, {3, 4}, {5}});
    check("triples", std::vector<int>{1, 2, 3, 4, 5, 6}, 3, Chunks{{1, 2, 3}, {4, 5, 6}});
    check("empty", std::vector<int>{}, 3, Chunks{});
    check("size-one", std::vector<int>{7, 8, 9}, 1, Chunks{{7}, {8}, {9}});
    check("size-larger", std::vector<int>{1, 2}, 5, Chunks{{1, 2}});
    check("size-equal", std::vector<int>{1, 2, 3}, 3, Chunks{{1, 2, 3}});
    check("last-shorter", std::vector<int>{1, 2, 3, 4}, 3, Chunks{{1, 2, 3}, {4}});
    check("negative", std::vector<int>{-1, -2, -3}, 2, Chunks{{-1, -2}, {-3}});
    check("extremes", std::vector<int>{(-2147483647 - 1), 2147483647, 0}, 2, Chunks{{(-2147483647 - 1), 2147483647}, {0}});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Chunks.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

import java.util.Arrays;

final class Chunks {
  private Chunks() {}

  /** Returns the chunks of items with size items each; the last chunk can be shorter. */
  static int[][] chunks(int[] items, int size) {
    int count = items.length / size + (items.length % size != 0 ? 1 : 0);
    int[][] out = new int[count][];
    for (int k = 0; k < count; k++) {
      int from = k * size;
      out[k] = Arrays.copyOfRange(items, from, Math.min(from + size, items.length));
    }
    return out;
  }
}
ChunksTest.java 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class ChunksTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("pairs", new int[] {1, 2, 3, 4, 5}, 2, new int[][] {{1, 2}, {3, 4}, {5}}),
        Arguments.of("triples", new int[] {1, 2, 3, 4, 5, 6}, 3, new int[][] {{1, 2, 3}, {4, 5, 6}}),
        Arguments.of("empty", new int[] {}, 3, new int[][] {}),
        Arguments.of("size-one", new int[] {7, 8, 9}, 1, new int[][] {{7}, {8}, {9}}),
        Arguments.of("size-larger", new int[] {1, 2}, 5, new int[][] {{1, 2}}),
        Arguments.of("size-equal", new int[] {1, 2, 3}, 3, new int[][] {{1, 2, 3}}),
        Arguments.of("last-shorter", new int[] {1, 2, 3, 4}, 3, new int[][] {{1, 2, 3}, {4}}),
        Arguments.of("negative", new int[] {-1, -2, -3}, 2, new int[][] {{-1, -2}, {-3}}),
        Arguments.of("extremes", new int[] {-2147483648, 2147483647, 0}, 2, new int[][] {{-2147483648, 2147483647}, {0}}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void chunks(String name, int[] items, int size, int[][] want) {
    // assertArrayEquals compares the inner arrays by their items.
    assertArrayEquals(want, Chunks.chunks(items, size));
  }
}
chunks.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

#include "chunks.h"

size_t chunk_count(size_t n, size_t size) {
    // (n + size - 1) / size can wrap around when n is near SIZE_MAX.
    return n / size + (n % size != 0);
}

size_t chunks(const int *items, size_t n, size_t size, struct chunk *out) {
    size_t k = 0;
    for (size_t i = 0; i < n; i += size) {
        out[k].start = items + i;
        out[k].len = n - i < size ? n - i : size;
        k++;
        if (n - i <= size) {
            break;
        }
    }
    return k;
}
chunks.h 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

#ifndef CHUNKS_H
#define CHUNKS_H

#include <stddef.h>

struct chunk {
    const int *start;
    size_t len;
};

// chunk_count returns the number of chunks of n items with size items each.
// size must be at least 1.
size_t chunk_count(size_t n, size_t size);

// chunks writes the chunks of items[0..n) to out and returns their number. Each
// chunk points into items. out must have room for chunk_count(n, size) chunks.
size_t chunks(const int *items, size_t n, size_t size, struct chunk *out);

#endif
test_chunks.c 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

#include "chunks.h"

#include <stdint.h>
#include <stdio.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

// An empty list has a 0 in it, because C has no empty array. The counts give
// the real lengths. LENS has the length of each chunk.
#define CHECK(name, n, given, size, m, lens)                                   \
    do {                                                                       \
        const int g[] = given;                                                 \
        const size_t w[] = lens;                                               \
        struct chunk out[sizeof g / sizeof g[0]];                              \
        const size_t want_n = m;                                               \
        size_t k = chunks(g, n, size, out);                                    \
        int ok = k == want_n && chunk_count(n, size) == want_n;                \
        size_t at = 0;                                                         \
        for (size_t i = 0; ok && i < want_n; i++) {                            \
            ok = out[i].start == g + at && out[i].len == w[i];                 \
            at += w[i];                                                        \
        }                                                                      \
        if (!ok) {                                                             \
            fprintf(stderr, "case %s failed\n", name);                         \
            failures++;                                                        \
        }                                                                      \
    } while (0)

int main(void) {
    CHECK("pairs", 5, L(1, 2, 3, 4, 5), 2, 3, L(2, 2, 1));
    CHECK("triples", 6, L(1, 2, 3, 4, 5, 6), 3, 2, L(3, 3));
    CHECK("empty", 0, L(0), 3, 0, L(0));
    CHECK("size-one", 3, L(7, 8, 9), 1, 3, L(1, 1, 1));
    CHECK("size-larger", 2, L(1, 2), 5, 1, L(2));
    CHECK("size-equal", 3, L(1, 2, 3), 3, 1, L(3));
    CHECK("last-shorter", 4, L(1, 2, 3, 4), 3, 2, L(3, 1));
    CHECK("negative", 3, L(-1, -2, -3), 2, 2, L(2, 1));
    CHECK("extremes", 3, L((-2147483647 - 1), 2147483647, 0), 2, 2, L(2, 1));
    if (chunk_count(SIZE_MAX, 2) != SIZE_MAX / 2 + 1) {
        fprintf(stderr, "chunk_count(SIZE_MAX, 2) failed\n");
        failures++;
    }
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Chunks.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

using System.Linq;

public static class Chunks
{
    // Split returns the chunks of items with size items each; the last chunk can be shorter.
    public static int[][] Split(int[] items, int size)
    {
        return items.Chunk(size).ToArray();
    }
}
ChunksTests.cs 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

using System;
using Xunit;

public sealed class ChunksTests
{
    public static TheoryData<string, int[], int, int[][]> Cases => new()
    {
        { "pairs", new int[] { 1, 2, 3, 4, 5 }, 2, new int[][] { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 5 } } },
        { "triples", new int[] { 1, 2, 3, 4, 5, 6 }, 3, new int[][] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } } },
        { "empty", new int[0], 3, new int[0][] },
        { "size-one", new int[] { 7, 8, 9 }, 1, new int[][] { new[] { 7 }, new[] { 8 }, new[] { 9 } } },
        { "size-larger", new int[] { 1, 2 }, 5, new int[][] { new[] { 1, 2 } } },
        { "size-equal", new int[] { 1, 2, 3 }, 3, new int[][] { new[] { 1, 2, 3 } } },
        { "last-shorter", new int[] { 1, 2, 3, 4 }, 3, new int[][] { new[] { 1, 2, 3 }, new[] { 4 } } },
        { "negative", new int[] { -1, -2, -3 }, 2, new int[][] { new[] { -1, -2 }, new[] { -3 } } },
        { "extremes", new int[] { -2147483648, 2147483647, 0 }, 2, new int[][] { new[] { -2147483648, 2147483647 }, new[] { 0 } } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] items, int size, int[][] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Chunks.Split(items, size));
    }

    [Fact]
    public void SizeBelowOne()
    {
        Assert.Throws<ArgumentOutOfRangeException>(() => Chunks.Split(new[] { 1 }, 0));
    }
}
chunks.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

/**
 * @param {number[]} items
 * @param {number} size at least 1
 * @returns {number[][]}
 */
export function chunks(items, size) {
  const out = [];
  for (let i = 0; i < items.length; i += size) {
    // slice makes a copy and stops at the end of the array.
    out.push(items.slice(i, i + size));
  }
  return out;
}
chunks.test.js 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { chunks } from "./chunks.js";

const cases = [
  ["pairs", [1, 2, 3, 4, 5], 2, [[1, 2], [3, 4], [5]]],
  ["triples", [1, 2, 3, 4, 5, 6], 3, [[1, 2, 3], [4, 5, 6]]],
  ["empty", [], 3, []],
  ["size-one", [7, 8, 9], 1, [[7], [8], [9]]],
  ["size-larger", [1, 2], 5, [[1, 2]]],
  ["size-equal", [1, 2, 3], 3, [[1, 2, 3]]],
  ["last-shorter", [1, 2, 3, 4], 3, [[1, 2, 3], [4]]],
  ["negative", [-1, -2, -3], 2, [[-1, -2], [-3]]],
  ["extremes", [-2147483648, 2147483647, 0], 2, [[-2147483648, 2147483647], [0]]],
];

for (const [name, items, size, want] of cases) {
  test(name, () => {
    assert.deepEqual(chunks(items, size), want);
  });
}
chunks.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

export function chunks(items: readonly number[], size: number): number[][] {
  const out: number[][] = [];
  for (let i = 0; i < items.length; i += size) {
    // slice makes a copy and stops at the end of the array.
    out.push(items.slice(i, i + size));
  }
  return out;
}
chunks.test.ts 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { chunks } from "./chunks.ts";

const cases: [string, number[], number, number[][]][] = [
  ["pairs", [1, 2, 3, 4, 5], 2, [[1, 2], [3, 4], [5]]],
  ["triples", [1, 2, 3, 4, 5, 6], 3, [[1, 2, 3], [4, 5, 6]]],
  ["empty", [], 3, []],
  ["size-one", [7, 8, 9], 1, [[7], [8], [9]]],
  ["size-larger", [1, 2], 5, [[1, 2]]],
  ["size-equal", [1, 2, 3], 3, [[1, 2, 3]]],
  ["last-shorter", [1, 2, 3, 4], 3, [[1, 2, 3], [4]]],
  ["negative", [-1, -2, -3], 2, [[-1, -2], [-3]]],
  ["extremes", [-2147483648, 2147483647, 0], 2, [[-2147483648, 2147483647], [0]]],
];

for (const [name, items, size, want] of cases) {
  test(name, () => {
    assert.deepEqual(chunks(items, size), want);
  });
}
chunks.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

// Package chunks splits a slice into chunks of a fixed size.
package chunks

import "slices"

// Chunks returns the chunks of items with size items each; the last chunk can
// be shorter. The chunks share the array of items, but each chunk has no
// capacity past its length, so an append to a chunk does not change items.
func Chunks(items []int, size int) [][]int {
	return slices.Collect(slices.Chunk(items, size))
}
chunks_test.go 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

package chunks

import (
	"slices"
	"testing"
)

var cases = []struct {
	name  string
	items []int
	size  int
	want  [][]int
}{
	{"pairs", []int{1, 2, 3, 4, 5}, 2, [][]int{{1, 2}, {3, 4}, {5}}},
	{"triples", []int{1, 2, 3, 4, 5, 6}, 3, [][]int{{1, 2, 3}, {4, 5, 6}}},
	{"empty", []int{}, 3, [][]int{}},
	{"size-one", []int{7, 8, 9}, 1, [][]int{{7}, {8}, {9}}},
	{"size-larger", []int{1, 2}, 5, [][]int{{1, 2}}},
	{"size-equal", []int{1, 2, 3}, 3, [][]int{{1, 2, 3}}},
	{"last-shorter", []int{1, 2, 3, 4}, 3, [][]int{{1, 2, 3}, {4}}},
	{"negative", []int{-1, -2, -3}, 2, [][]int{{-1, -2}, {-3}}},
	{"extremes", []int{-2147483648, 2147483647, 0}, 2, [][]int{{-2147483648, 2147483647}, {0}}},
}

func TestChunks(t *testing.T) {
	for _, c := range cases {
		got := Chunks(c.items, c.size)
		if !slices.EqualFunc(got, c.want, slices.Equal[[]int]) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}

func TestAppendDoesNotChangeItems(t *testing.T) {
	items := []int{1, 2, 3, 4}
	c := Chunks(items, 2)
	_ = append(c[0], 99)
	if !slices.Equal(items, []int{1, 2, 3, 4}) {
		t.Errorf("the input changed: %v", items)
	}
}
chunks.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

/// Returns the chunks of items with size items each; the last chunk can be shorter.
/// Panics if size is 0.
pub fn chunks(items: &[i32], size: usize) -> Vec<Vec<i32>> {
    items.chunks(size).map(<[i32]>::to_vec).collect()
}
tests/chunks_test.rs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-in-chunks/.

use algo_iterate_in_chunks::chunks;

#[test]
fn cases() {
    let cases: Vec<(&str, &[i32], usize, Vec<Vec<i32>>)> = vec![
        ("pairs", &[1, 2, 3, 4, 5], 2, vec![vec![1, 2], vec![3, 4], vec![5]]),
        ("triples", &[1, 2, 3, 4, 5, 6], 3, vec![vec![1, 2, 3], vec![4, 5, 6]]),
        ("empty", &[], 3, vec![]),
        ("size-one", &[7, 8, 9], 1, vec![vec![7], vec![8], vec![9]]),
        ("size-larger", &[1, 2], 5, vec![vec![1, 2]]),
        ("size-equal", &[1, 2, 3], 3, vec![vec![1, 2, 3]]),
        ("last-shorter", &[1, 2, 3, 4], 3, vec![vec![1, 2, 3], vec![4]]),
        ("negative", &[-1, -2, -3], 2, vec![vec![-1, -2], vec![-3]]),
        ("extremes", &[-2147483648, 2147483647, 0], 2, vec![vec![-2147483648, 2147483647], vec![0]]),
    ];
    for (name, items, size, want) in cases {
        assert_eq!(chunks(items, size), want, "{name}");
    }
}

#[test]
#[should_panic]
fn size_zero_panics() {
    chunks(&[1], 0);
}
chunks.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-in-chunks/.

# chunks SIZE ITEM...
# Prints one line for each chunk of SIZE items, with the items separated by
# spaces. The last chunk can be shorter. SIZE must be at least 1.
chunks() {
  local size=$1 i
  shift
  local -a items=("$@")
  for ((i = 0; i < ${#items[@]}; i += size)); do
    # ${items[@]:i:size} is size items from index i, not a part of a string.
    printf '%s\n' "${items[*]:i:size}"
  done
}
test_chunks.bats 29 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-in-chunks/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/chunks.sh"
}

check() { # check WANT SIZE ITEM...
  local want got
  # %b turns each \n in WANT into a newline. The x keeps the trailing
  # newlines, which $(...) removes.
  want=$(printf '%b' "$1"; printf x)
  shift
  got=$(chunks "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "pairs" { check "1 2\n3 4\n5\n" 2 1 2 3 4 5; }
@test "triples" { check "1 2 3\n4 5 6\n" 3 1 2 3 4 5 6; }
@test "empty" { check "" 3; }
@test "size-one" { check "7\n8\n9\n" 1 7 8 9; }
@test "size-larger" { check "1 2\n" 5 1 2; }
@test "size-equal" { check "1 2 3\n" 3 1 2 3; }
@test "last-shorter" { check "1 2 3\n4\n" 3 1 2 3 4; }
@test "negative" { check "-1 -2\n-3\n" 2 -1 -2 -3; }
@test "extremes" { check "-2147483648 2147483647\n0\n" 2 -2147483648 2147483647 0; }

References

  1. The Python Standard Library, itertools, itertools.batched()
  2. .NET API reference, Enumerable.Chunk method, Exceptions, Remarks
  3. The Python Standard Library, Built-in Functions, zip()
  4. MDN Web Docs, Array.prototype.splice(), Description
  5. Java SE 25 API, Interface List, subList(int, int)
  6. Go standard library, package slices, func Chunk
  7. Rust standard library, primitive type slice, chunks_exact
  8. cppreference.com, Arithmetic operators (C), Overflows
  9. cppreference.com, std::span::subspan, Description
  10. Bash Reference Manual, 3.5.3 Shell Parameter Expansion

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source