Python is a great programming language. You can learn it easily as it is a high-level programming language and is just like the English language. Python list is a data structure that is ordered and mutable. It is the most commonly used data structure in python. In this entire tutorial, you will learn how to split the list into chunks in python using various ways.
Method 1: Using python generator
The first method I will show you is the use of Python Generator. Python generator allows defining a function that acts as an iterator. Rather than returning the value it generates the value and yields the result. Let’s define a generator function that will split the list into chunks.
def list_chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n]
The list I will use for splitting is below.
my_list = [1,2,3,4,5,6,7,8,9]
Suppose I want to split the list into chunks of 2 then I will pass my list with n as 2 value.
In the same, you can split the list into chunks of 3.
Method 2: Split List into Chunks using List Comprehension
Instead of using the function, you can split the list into chunks using list comprehension. List comprehension allows you to create and define lists using existing lists. List comprehension works faster than the normal functions and loops are used to create lists.
Let’s apply the list comprehension on the same list I created in step 1.
Chunks of Two
lst = [1,2,3,4,5,6,7,8,9] n=2 chunks = [lst[i:i + n] for i in range(0, len(lst), n)] print(chunks)
Chunks of Four
lst = [1,2,3,4,5,6,7,8,9] n=4 chunks = [lst[i:i + n] for i in range(0, len(lst), n)] print(chunks)
Method 3: Split List into Chunks in Python using Numpy
You can also use Numpy to split a list into chunks in python. But each chunk will be of NumPy array type. NumPy is a Python library that supports large multi-dimensional arrays and does computational works on them. You can convert the NumPy array to a list by typecasting the array with the list() method.
import numpy as np my_list = [1,2,3,4,5,6,7,8,9] print(np.array_split(my_list,3))
You can see you have got the list of chunks as NumPy array type. Just use list(array[1,2,3]) to convert the NumPy.array type to list.
Splitting list into chunks in python is commonly used in NLP or NLTK. In NLP you split the strings or sentences into bigrams, trigrams e.t.c for text pre-processing. Thus learning how to form chunks is important. These are the methods that you can use to split the list into chunks. I hope you have liked this tutorial. If you have any doubt then you can contact for more help.