How to Split a List into N Sublists in Python?

Estimated read time 2 min read

To split a list into N sublists in Python, you can use a loop with slicing. Here’s an example that splits a list into n sublists, where n is the number of sublists you want to create:

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

# Calculate the size of each sublist
sublist_size = len(my_list) // n
remainder = len(my_list) % n

# Split the list into sublists of a specific size
sublists = []
start = 0
for i in range(n):
    size = sublist_size + (i < remainder)
    start += size

print(sublists)  # Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]

In this example, we define a list my_list and a variable n that specifies the number of sublists to create. We calculate the size of each sublist by dividing the length of the list by n, and use the remainder to add an extra element to the first remainder sublists if necessary.

We then use a loop to iterate over n sublists, and use slicing to extract each sublist from the original list. The start variable keeps track of the starting index of each sublist.

The resulting sublists are stored in the sublists variable.

Note that if the length of the original list is not evenly divisible by n, the last sublist will be shorter than the others.

This method should work for splitting a list into N sublists in Python.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply