How to Group a List into Chunks in Python

Split a list into smaller groups of a fixed size using a reusable function with a default parameter.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 15 views 0 copies

Python code

14 lines
Python 3.9+
def make_groups(numbers, group_size=2):
    """Splits a list into smaller groups of a given size."""
    groups = []
    for i in range(0, len(numbers), group_size):
        groups.append(numbers[i:i + group_size])
    return groups


if __name__ == "__main__":
    data = [1, 2, 3, 4, 5, 6, 7]

    print("Default size (2):", make_groups(data))
    print("Custom size (3):", make_groups(data, 3))
    print("Custom size (1):", make_groups(data, 1))

Output

stdout
Default size (2): [[1, 2], [3, 4], [5, 6], [7]]
Custom size (3): [[1, 2, 3], [4, 5, 6], [7]]
Custom size (1): [[1], [2], [3], [4], [5], [6], [7]]

How it works

The make_groups function uses a for loop with range(0, len(numbers), group_size) to step through the list in fixed-size jumps. Each slice numbers[i:i + group_size] grabs one group, including a possibly shorter final slice when the list length isn't a multiple of the group size. The group_size=2 default means callers can use the function with just one argument, while still allowing a custom chunk size when needed. This pattern is a clean, beginner-friendly way to separate function logic from the main script using an if __name__ == "__main__" block.

Common mistakes

  • Using `group_size` as 0, which causes a `ValueError` from zero-step in `range()`
  • Assuming all groups are the same size when the list length isn't divisible by the group size
  • Mutating the original list inside the loop instead of creating new slices

Variations

  1. Use a list comprehension: `[numbers[i:i + group_size] for i in range(0, len(numbers), group_size)]`
  2. Return an iterator with a generator expression to handle large lists lazily

Real-world use cases

  • Batching database records into chunks for bulk inserts or row processing.
  • Splitting a large API payload into pages for paginated requests.
  • Grouping log entries into time buckets for batch analysis.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.