numpy.array_split
Функция array_split() разбивает массив на несколько подмассивов.
Единственное отличие данной функции от функции split заключается в снятии ограничений на параметр indices_or_sections . В функции array_split параметр indices_or_sections может быть равен числу, которое не делит нацело длинну указанной оси.
Параметры: a — массив NumPy Массив, который необходимо разбить на подмассивы. indices_or_sections — целое число или одномерный массив
Если указанная ось массива a имеет длинну L, и в качестве параметра indices_or_sections указано число n, то сначала будет возвращено L%n подмассивов длинной L//n + 1 и n — L%n подмассивов длинной L//n .
Если параметр indices_or_sections является одномерным массивом отсортированных по возрастанию целых чисел, то вдоль указанной оси массив будет разбит на соответствующие указанным числам промежутки. Например, если указан массив [2,4,7] , то это будет соответствовать промежуткам [:2], [2:4], [4:7], [7:] .
Если некоторое число в параметре indices_or_sections превышает размер массива вдоль указанной оси, то будет возвращен пустой массив.
axis — целое число (необязательный) Определяет ось вдоль которой происходит разбиение массива. По умолчанию равен 0 (первая ось). Возвращает: list of ndarrays — список массивов NumPy Список подмассивов исходного массива a.
Python: Split a List (In Half, in Chunks)
In this tutorial, you’ll learn how to use Python to split a list, including how to split it in half and into n equal-sized chunks. You’ll learn how to split a Python list into chunks of size n , meaning that you’ll return lists that each contain n (or fewer if there are none left) items. Knowing how to work with lists in Python is an important skill to learn.
By the end of this tutorial, you’ll have learned:
- How to split a list in half in Python
- How to split a list into chunks in Python
- How to split a list at a particular index position in Python
- How to use NumPy to split a list in Python
The Quick Answer: Use List Indexing to Split a List in Python

Table of Contents
How to Access a Python List by Its Index
One of the many wonderful properties of lists is that they are ordered. This means that we can access an item, or a range of items, by its index. Let’s see how Python list indices work:

We can see here that Python lists have both a positive index as well as a negative index. A positive index begins at position 0, meaning the first item. A negative list index begins at -1, allowing you to retrieve the last item of a list.
Similarly, you can access ranges of data within a list using list slicing. This can be done by using the : colon character, which allows you to select items from a specific position up to a specific position.
How to Split a Python List in Half
You can easily split a Python list in half using list indexing. As you learned above, you can select multiple items in a list using list slicing. Let’s see how we can use list slicing to split a list in half:
Let’s break down what we did in the code above:
- We created a list a_list , which contains ten different items
- We then created an integer variable, half_length , which is the result of dividing the length of the list by two using integer division
- We then assigned variables, first_half and second_half , which sliced the lists up to and from the half variable
In the following section, you’ll learn how to split a list into different sized chunks in Python.
Split Lists into Chunks Using a For-Loop
For-loops in Python are an incredibly useful tool to use. They make a lot of Python methods easy to implement, as well as easy to understand. For this reason, let’s start off by using a for-loop to split our list into different chunks.
One of the ways you can split a list is into n different chunks. Let’s see how we can accomplish this by using a for loop:
Let’s take a look at what we’ve done here:
- We instantiate two lists: a_list , which contains the items of our original list, and chunked_list , which is empty
- We also declare a variable, chunk_size , which we’ve set to three, to indicate that we want to split our list into chunks of size 3
- We then loop over our list using the range function. What we’ve done here is created items from 0, through to the size of our list, iterating at our chunk size. For example, our range function would read range(0, 11, 3) , meaning that we’d loop over using items 0,3,6,9 .
- We then index our list from i:i+chunk_size , meaning the first loop would be 0:3 , then 3:6 , etc.
- These indexed lists are appended to our list
We can see that this is a fairly straightforward way of breaking a Python list into chunks. Next, you’ll learn how to do accomplish this using Python list comprehensions.
Split Python Lists into Chunks Using a List Comprehension
In many cases, Python for-loops can be rewritten in a more Pythonic way by writing them as one-liners called list comprehensions. List comprehensions in Python have a number of useful benefits over for-loops, including not having to instantiate an empty list first, and not having to break your for-loop over multiple lines.
Let’s see how we can write a Python list comprehension to break a list into chunks:
Before we break down this code, let’s see what the basic syntax of a Python list comprehension looks like:

Now let’s break down our code to see how it works:
- We declare a variable chunk_size to determine how big we want our chunked lists to be
- For our list comprehensions expression, we index our list based on the i th to the i+chunk_size th position
- We use this expression to iterate over every item in the output of the range() object that’s created based on range(0, len(our_list), chunk_size , which in this case would be 0,3,6,9
While this approach is a little faster to type, whether or not it is more readable than a for-loop, is up for discussion. Let’s learn how to split our Python lists into chunks using numpy.
Want to learn more? Check out my in-depth tutorial about Python list comprehensions by clicking here!
Split Lists into Chunks Using NumPy
Numpy is an amazing Python library that makes mathematical operations significantly easier. That being said, NumPy also works with a list-like object, called NumPy arrays, that make working with lists much easier. These NumPy arrays come packaged with lots of different methods to manipulate your arrays.
It’s important to note that this method will only work with numeric values.
In this section of the tutorial, we’ll use the NumPy array_split() function to split our Python list into chunks. This function allows you to split an array into a set number of arrays.
Let’s see how we can use NumPy to split our list into 3 separate chunks:
This is a fairly long way of doing things, and we can definitely cut it down a little bit. Let’s see how that can be done:
Let’s break this down a little bit:
- We turn our list into a Numpy array
- We split our array into n number of arrays using the np.array_split() function
- Finally, we use a list comprehension to turn all the arrays in our list of arrays back into lists.
Want to learn more about division in Python? Check out my tutorial on how to use floored integer division and float division in Python in this tutorial here.
Split Lists into Chunks Using Itertools
Let’s see how we can use itertools library to split a list into chunks. In particular, we can use the zip_longest function to accomplish this.
Let’s see how we can do this:
We can see here that we can have a relatively simple implementation that returns a list of tuples. Notice one of the things that are done here is split the list into chunks of size n, rather than into n chunks.
Frequently Asked Questions
The best way to split a Python list is to use list indexing, as it gives you huge amounts of flexibility.
The NumPy array_split() function allows you to easily split arrays into a given number of arrays. However, the function only works with numeric values (as NumPy arrays can only contain numeric values).
Conclusion
In this post, you learned how to split a Python list into chunks. You learned how to accomplish splitting a Python list into chunks of size n or into n number chunks . You learned how to do this using a for-loop, using list comprehensions, NumPy and itertools.
4 Easy Ways to Split List in Python
There are the following methods to to split a list in Python.
- Using len(): The len() method returns the length of the list and uses the floor divide.
- Using list comprehension: Split the list into chunks, and provide the N to the list comprehension.
- Using for loop: Use a for loop to split the list into different chunks.
- Using numpy array_split(): It allows you to split an array into a set number of arrays.
Method 1: Using the len() method
To split a list in Python, use the len() method with iterable as a list to find its length and then floor divide the length by 2 using the “//” operator to find the middle_index of the list.
Output
As you can see from the output, we split the list in exact half. We used the colon operator(:) to access the first and second half of the split list.
How to split a list into n parts in Python
To split a list into n parts in Python, use the numpy.array_split() function.
The np.split() function splits the array into multiple sub-arrays.
The numpy array_split() method returns the list of n Numpy arrays, each containing approximately the same number of elements from the list.
Output
In this example, we split the list into 3 parts.
Splitting a List Into Even Chunks of N Elements in Python
A list can be split based on the size of the chunk defined. This means that we can determine the size of the chunk.
If the subset of a list doesn’t fit the size of the defined chunk, fillers need to be inserted in place of the empty element holders.
Therefore, we will use None as a filter to fill those empty element holders.
Output
The list has been split into equal chunks of 7 elements each.
The above list_split() function takes the arguments: listA for the list and chunk_size for a number to split by. Then, the function iterates through the list with an increment of the chunk size n.
Each chunk is expected to have the size given as an argument. If there aren’t enough elements to split the same size, the remaining unused elements are filled with None.
Method 2: Using list comprehension
Using list comprehension, we can split an original list and create chunks. To split the list into chunks, provide the N to the list comprehension syntax, and it will create a new list with N chunks of elements.
Output
You can see that we split a list into chunks of 3 elements. You can divide the list into chunks of 2 elements or four elements. Pass the split_size, which is N in our case.
Method 3: Using for loop
Use a for loop to split the list into different chunks. Define the chunk size of the list, and it will create a list of chunks of that exact size.
Output
Method 4: Using numpy array_split()
The np.array_split() is a numpy library function that splits the list into chunks. It allows you to split an array into a set number of arrays.
Output
FAQ
How to split a list into multiple lists in Python?
Use list slicing to split a list into multiple lists.
Output
How to split a list into a specific number of sublists in Python?
Use a list slicing in combination with the range() function to split a list into a specific number of sublists.
Output
Conclusion
To split the list in Python, you can use the built-in len() function in combination with floor divide the length by 2 using the // operator to find the middle_index of the list. You can also use the for loop, list comprehension, or numpy array_split() approaches to split the list.
numpy.split
Разделите массив на несколько подмассивов в виде представлений в ary .
Parameters aryndarray
Массив разделить на подмассивы.
index_or_sections int или одномерный массив
Если indices_or_sections является целым числом N, массив будет разделен на N равных массивов по axis . Если такое разделение невозможно, возникает ошибка.
Если indices_or_sections представляет собой одномерный массив отсортированных целых чисел, записи указывают, где вдоль axis массив разбивается. Например, [2, 3] для axis=0 приведет к
- ary[:2]
- ary[2:3]
- ary[3:]
Если индекс превышает размер массива по axis , соответственно возвращается пустой подмассив.
axisint, optional
По умолчанию ось,по которой происходит разделение,равна 0.
Returns подмассивов список ndarrays
Список подмассивов как представлений в ary .
Если indices_or_sections задано как целое число, но разделение не приводит к равному разделению.
Разделите массив на несколько подмассивов одинакового или почти одинакового размера.Не вызывает исключений,если равное деление невозможно.