Sling Academy
Home/Python/Python: Separate a List into Equally Sized Chunks

Python: Separate a List into Equally Sized Chunks

Last updated: July 03, 2023

This concise, straight-to-the-point article will walk you through a couple of different approaches to splitting a given Python list into equally sized chunks (the last chunk might contain fewer elements than others if the length of the original list is not evenly divisible by the number of chunks).

The size of each chunk is fixed

This technique is useful when the size of each resulting chunk is predetermined, but the number of chunks is unknown.

The main idea here is to use list comprehension to iterate over the list indices from 0 to the length of the list with a step size of n (the size of each chunk). For each index i, use the slice notation list[i:i+n] to extract a sublist of length n from the original list and append it to the resulting list.

Example:

# Define the original list and the chunk size
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
n = 3

# Use list slicing and list comprehension to split the list into chunks
chunks = [my_list[i:i+n] for i in range(0, len(my_list), n)]

# Print the resulting list of chunks
print(chunks)

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

You can also define a reusable function like this:

def split_list_into_chunks(input_list, chunk_size):
    return [input_list[i:i+chunk_size] for i in range(0, len(input_list), chunk_size)]

The number of ouput chunks is fixed

In case you want to get a certain number of chunks (the size of each chunk will depend on the length of the input list), then this is the solution for you. The steps are:

  1. Determine the chunk size by dividing the length of the list by the desired number of chunks.
  2. Use a list comprehension to iterate over the list and create sublists of the specified chunk size.
  3. Handle the case when the length of the list is not evenly divisible by the chunk size by appending the remaining elements to the last chunk.
  4. Return the list of chunks.

Code example:

import math

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Split in 4 chunks
num_chunks = 4

# Calculate the chunk size as an integer
chunk_size = math.ceil(len(my_list) / num_chunks)

chunks = [my_list[i:i + chunk_size] for i in range(0, len(my_list), chunk_size)]

print(chunks)

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

To simplify the task in the future, we can create a reusable function like this:

import math

def divide_list_into_chucks(input_list, num_chunks):
    chunk_size = math.ceil(len(input_list) / num_chunks)
    return [input_list[i:i + chunk_size] for i in range(0, len(input_list), chunk_size)]

That’s it. Happy coding!

Next Article: Python: Declaring Lists with Type Hints (7 Examples)

Previous Article: Python map() function: Tutorial & examples

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types