Skip to content

Python Split a list into evenly sized chunks? AlixaProDev Spark By {Examples}

How to split a list into evenly-sized elements in Python? To split the list evenly use methods like slicing, zip(), iter(), numpy.array_split(), list comprehension, and a lot more. In this article, we will explain all these methods to split a list into equally sized chunks as each method has its own advantages and disadvantages. 1.  Read More Python, Python Tutorial, Python List Examples Spark By {Examples} 

How to split a list into evenly-sized elements in Python? To split the list evenly use methods like slicing, zip(), iter(), numpy.array_split(), list comprehension, and a lot more. In this article, we will explain all these methods to split a list into equally sized chunks as each method has its own advantages and disadvantages.

1. Quick Examples – Split a List into Evenly Sized Chunks

Below are quick examples of how to split a list into evenly sized chunks using various methods. These List examples will give you an overview of the different approaches.

# Quick examples of spliting a list into evenly sized chunks
import numpy as np
import itertools
from functools import partial

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
chunk_size = 3

# Example 1 : Using list slicing
def chunkify(lst, chunk_size):
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]

result = chunkify(lst, chunk_size)
print(“Using list slicing:”, result)

# Example 2: Using numpy.array_split()
result = np.array_split(lst, len(lst)/chunk_size)
print(“Using numpy.array_split():”, result)

# Example 3: Using yield statement and iterators
def chunkify(lst, chunk_size):
for i in range(0, len(lst), chunk_size):
yield lst[i:i+chunk_size]

result = list(chunkify(lst, chunk_size))
print(“Using yield statement and iterators:”, result)

2. List Slicing – Split a List into Evenly Sized Chunks

List slicing is a common way to split a list into equally sized chunks in Python. The basic idea is to use the slice notation to extract sublists of the desired length.

The following is using list slicing with list comprehension to split a list into evenly sized chunks.

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

When using this method is that the final sublist may have fewer than chunk_size elements, if the length of the original list is not evenly divisible by chunk_size.

See the following example:

# Initialize list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Chunk size 3
chunk_size = 3

# Split the list
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]]

Alternatively, you can write the above example using for loop instead of list comprehension. Below is an example that is very much easy to understand.

# Split list equally
chunked_list = []
for i in range(0, len(my_list), chunk_size):
chunked_list.append(my_list[i:i+chunk_size])
print(chunked_list)

Both methods will yield the same results.

3. Using numpy.array_split()

Using numpy.array_split() is another easy and efficient way to split a list into evenly sized chunks. numpy.array_split() is a function provided by the NumPy library that splits an array (or list) into multiple sub-arrays of equal or near-equal size.

Syntax for using numpy.array_split():

# Syntax
numpy.array_split(array, num_of_splits)

You can use the following example as a reference:

# Split the list into three evenly-sized chunks
chunks = np.array_split(my_list, 3)

# Print the resulting chunks
for chunk in chunks:
print(chunk)

4. Using zip() and iter()

We can use a combination of both zip() and iter() function to split a list into evenly sized chunks. The zip() function is used to combine two or more iterable objects and return an iterator of tuples. The iter() function returns an iterator for an object.

Syntax for using zip() and iter():

# Using zip() with iter
def chunks(lst, n):
“””Yield successive n-sized chunks from lst.”””
it = iter(lst)
return zip(*[it] * n)
result = list(chunks(lst, chunk_size))

This method may not be as efficient as some of the other methods if the original list is very large since it creates multiple copies of the original list.

5. Yield Keyword – Split List into Evenly Sized Chunks

The yield statement with iterators is another way to split a list into evenly sized chunks in Python. In this method, we define a generator function that yields the next chunk of the list each time it is called. This approach is memory-efficient as it does not create any additional copies of the original list.

# Split List into Evenly Sized Chunks
def chunks(lst, chunk_size):
for i in range(0, len(lst), chunk_size):
yield lst[i:i + chunk_size]

for chunk in chunks(my_list, chunk_size):
print(chunk)

# Output:
# [1, 2, 3]
# [4, 5, 6]
# [7, 8, 9]

6. Summary and Conclusion

We have covered multiple ways to split a list into evenly sized-chunks in Python. We have covered techniques ranging from basic list slicing to more advanced methods. If you have any questions or feedback, feel free to leave a comment below.

Happy coding!

 

Leave a Reply

Your email address will not be published. Required fields are marked *