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

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots