python - How to split a list into equally-sized chunks?

Python - How to split a list into equally-sized chunks?

To split a list into equally-sized chunks in Python, you can use various approaches depending on whether you want to handle any leftover elements differently or not. Here are a few methods using Python's standard library and techniques:

Method 1: Using List Comprehension

This method divides the list into chunks of a specified size using list comprehension.

def chunk_list(lst, chunk_size): return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] chunk_size = 3 chunks = chunk_list(my_list, chunk_size) print(chunks) 

Explanation:

  • chunk_list function: This function takes a list (lst) and a chunk size (chunk_size) as input.
  • List comprehension: [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] iterates over lst in steps of chunk_size, slicing it from i to i + chunk_size.
  • Result: This returns a list of chunks, each of size chunk_size. If the original list length isn't a multiple of chunk_size, the last chunk will have fewer elements.

Output:

For my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and chunk_size = 3, the output will be:

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

Method 2: Using itertools.islice

Another approach involves using itertools.islice, which allows you to slice iterables efficiently:

from itertools import islice def chunk_list(lst, chunk_size): return [list(islice(lst, i, i + chunk_size)) for i in range(0, len(lst), chunk_size)] # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] chunk_size = 3 chunks = chunk_list(my_list, chunk_size) print(chunks) 

Explanation:

  • chunk_list function: Similar to the previous example, but it uses islice to slice lst.
  • list(islice(lst, i, i + chunk_size)): This slices lst from i to i + chunk_size and converts the result to a list.
  • Result: Returns a list of chunks of size chunk_size, handling leftover elements in the last chunk.

Output:

The output will be the same as Method 1 for the given example.

Considerations:

  • Handling Leftovers: Both methods handle leftover elements by creating a smaller chunk for the last elements that don't fit evenly into chunk_size.
  • Edge Cases: Ensure chunk_size is greater than zero and less than or equal to the length of lst to avoid errors.

These methods provide flexible ways to split a list into equally-sized chunks in Python, accommodating various requirements and ensuring efficient use of resources. Choose the method that best fits your specific use case and coding style.

Examples

  1. Split a list into equal-sized chunks using plain Python

    • Description: Divide a list into chunks of equal size using basic Python without any external libraries.
    • Code:
      def split_list(lst, chunk_size): return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)] # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunked_list = split_list(my_list, 3) print(chunked_list) 
  2. Split a list into chunks of equal size using itertools

    • Description: Utilize Python's itertools module to split a list into chunks of equal size.
    • Code:
      from itertools import zip_longest def split_list(lst, chunk_size): it = iter(lst) return [list(filter(None, group)) for group in zip_longest(*([it] * chunk_size))] # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunked_list = split_list(my_list, 3) print(chunked_list) 
  3. Split a list into equal-sized chunks with padding if necessary

    • Description: Divide a list into chunks of equal size, padding the last chunk if it's smaller than the specified size.
    • Code:
      from itertools import zip_longest def split_list(lst, chunk_size): return list(zip_longest(*([iter(lst)] * chunk_size), fillvalue=None)) # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunked_list = split_list(my_list, 3) print(chunked_list) 
  4. Split a list into chunks of approximately equal size

    • Description: Split a list into chunks where each chunk has approximately the same number of elements.
    • Code:
      def split_list(lst, num_chunks): avg = len(lst) / float(num_chunks) out = [] last = 0.0 while last < len(lst): out.append(lst[int(last):int(last + avg)]) last += avg return out # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunked_list = split_list(my_list, 3) print(chunked_list) 
  5. Split a list into chunks using numpy

    • Description: Utilize NumPy to split a list into chunks of equal size, leveraging its array manipulation capabilities.
    • Code:
      import numpy as np def split_list(lst, chunk_size): return np.array_split(lst, len(lst) // chunk_size) # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunked_list = split_list(my_list, 3) print(chunked_list) 
  6. Split a list into chunks with itertools grouper

    • Description: Use itertools' grouper recipe to split a list into chunks of equal size.
    • Code:
      from itertools import zip_longest def grouper(iterable, n, fillvalue=None): args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) def split_list(lst, chunk_size): return list(grouper(lst, chunk_size)) # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunked_list = split_list(my_list, 3) print(chunked_list) 
  7. Split a list into chunks maintaining order

    • Description: Divide a list into chunks of equal size while maintaining the order of elements.
    • Code:
      from collections import deque def split_list(lst, chunk_size): it = iter(lst) chunk = list(deque(islice(it, chunk_size)) for _ in range(0, len(lst), chunk_size)) return chunk # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunked_list = split_list(my_list, 3) print(chunked_list) 
  8. Split a list into chunks with recursion

    • Description: Use a recursive approach to split a list into chunks of equal size.
    • Code:
      def split_list(lst, chunk_size): if not lst: return [] return [lst[:chunk_size]] + split_list(lst[chunk_size:], chunk_size) # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunked_list = split_list(my_list, 3) print(chunked_list) 
  9. Split a list into chunks using list comprehension

    • Description: Split a list into chunks of equal size using list comprehension for a concise approach.
    • Code:
      def split_list(lst, chunk_size): return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)] # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunked_list = split_list(my_list, 3) print(chunked_list) 
  10. Split a list into chunks with modulo operator

    • Description: Divide a list into chunks of equal size using the modulo operator for efficient slicing.
    • Code:
      def split_list(lst, chunk_size): return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)] # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunked_list = split_list(my_list, 3) print(chunked_list) 

More Tags

ormlite angular-router weak-references nlp git-filter-branch data-munging android-recyclerview curly-braces edid mongodb

More Programming Questions

More Auto Calculators

More Tax and Salary Calculators

More Animal pregnancy Calculators

More Date and Time Calculators