[Python] How to Split a List into N Groups

Sometimes, you need to divide a list into a specific number of groups (e.g., “split into 3 groups”) rather than chunks of a specific size (e.g., “3 items each”).

Since Python’s standard library does not provide a direct function for this type of “N-split,” you need to calculate the “number of elements per group” based on the total count and then slice the list.

This article explains how to split a list into a specified number of groups using math.ceil to keep the sizes as even as possible.

目次

Implementation Example: Team Assignments

In this scenario, we will assign 10 event participants to 3 teams (groups).

Source Code

import math

# List of 10 participants
participants = [
    "User_A", "User_B", "User_C", "User_D", "User_E",
    "User_F", "User_G", "User_H", "User_I", "User_J"
]

# Number of groups to split into (N)
num_groups = 3

# Calculate the number of elements (size) per group
# Use math.ceil to round up to cover remainders
# 10 / 3 = 3.33... -> Rounds up to 4
chunk_size = math.ceil(len(participants) / num_groups)

# Execute the split using list comprehension
# Use the calculated size as the step for range(start, stop, step)
teams = [
    participants[i : i + chunk_size] 
    for i in range(0, len(participants), chunk_size)
]

# Check results
print(f"Total Participants: {len(participants)}")
print(f"Number of Groups:   {num_groups} (Max {chunk_size} per team)")
print("-" * 30)

for idx, team in enumerate(teams, 1):
    print(f"Team {idx}: {team}")

Execution Result

Total Participants: 10
Number of Groups:   3 (Max 4 per team)
------------------------------
Team 1: ['User_A', 'User_B', 'User_C', 'User_D']
Team 2: ['User_E', 'User_F', 'User_G', 'User_H']
Team 3: ['User_I', 'User_J']

Explanation

Logic Details

  1. Determining the Size: We calculate the maximum size of each sub-list by computing len(list) / n and rounding up with math.ceil().
    • Example: When splitting 10 people into 3 teams, 10 / 3 = 3.33.
    • Rounding Up: We set the size to 4. This results in groups of 4, 4, and 2, covering all elements.
    • Rounding Down (Incorrect): If we rounded down to 3, we would get groups of 3, 3, and 3, totaling 9, leaving one person out.
  2. Splitting by Slicing: We use the calculated size as the step in the range() function to loop through the list and slice it into new sub-lists.

Note

This method uses a “fill from the start” approach. If the total number cannot be divided exactly, the last group will have fewer elements.

In the example above, Teams 1 and 2 have 4 members, while Team 3 has 2. If you require perfectly balanced distribution (e.g., 4, 3, 3), you would need more complex logic to distribute the remainder. However, for simple splitting, this method is the standard approach.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次