Partition n samples into k equal contiguous folds by index. For each fold f, the test indices are [f*fold_size, (f+1)*fold_size); the rest are train. Library: KFold(n_splits=k, shuffle=False) yields identical index splits. RESULT: list of test-index lists per fold.

By hand

With scikit-learn

KFold(n_splits=3, shuffle=False).split(range(n)) yields (train_idx, test_idx) pairs per fold; shuffle=False keeps contiguous test segments, matching the manual boundary split exactly.

naive.py
n = 6
k = 3
fold_size = n // k
folds = []
for f in range(k):
    start = f * fold_size
    end = start + fold_size
    test_idx = list(range(start, end))
    folds.append(test_idx)
print('RESULT:', folds)
library.py
from sklearn.model_selection import KFold
from dalib.display import set_display
set_display()

n = 6
kf = KFold(n_splits=3, shuffle=False)
test_folds = []
train_folds = []
for train_idx, test_idx in kf.split(range(n)):
    train_folds.append(train_idx.tolist())
    test_folds.append(test_idx.tolist())
print('train_folds:', train_folds)
print('RESULT:', test_folds)
train_folds: [[2, 3, 4, 5], [0, 1, 4, 5], [0, 1, 2, 3]]
RESULT: [[0, 1], [2, 3], [4, 5]]

Implementation notes

  • fold_size = n // k assumes n divisible by k. For uneven n, KFold distributes the extra samples to the first folds — this manual version does not handle that case.
  • Each fold rotates through the dataset: the union of all test folds covers every sample index exactly once.
  • Cross-reference: train-test-split-fixed (ch01) for a single holdout split. Cross-validation uses k splits to average out the variance of any one split; cross-reference compare-two-model-scores (this chapter) for using fold scores to pick a model.