In this comprehensive tutorial, we will explore various methods for splitting a list in Python. Lists, being mutable data types, can efficiently store collections of items. We will cover three distinct scenarios: splitting a list in half, dividing it into n sublists or parts, and breaking it into chunks. Additionally, we will delve into each case with illustrative examples.
If you wish to deepen your understanding of lists in Python, be sure to check out our Python List Tutorials
In Python, a single variable can contain multiple items by using lists. Lists are one of the four built-in data types for storing data collections in Python, with the other three being tuples, sets, and dictionaries, each serving its unique purpose.
A Brief Overview
1) Use list slicing with [:] to split a list in half.
2) Find the midpoint index by dividing the length by 2.
3) Create two new lists with [:mid] and [mid:] slicing.
Here in this tutorial, we will discuss the following cases.
Case 1: Given an input list, split it into two halves.
(a) When the list is symmetrical.
Output= [1,7,5,3] and [2,8,9,4]
(b) When the list is asymmetrical.
Output= [13,6,2,4,4] and [81,9,32,5,7,11]
Case 2: Given an input list, split it into n sublists.
Output= [5,3,2], [1,3,24], [5,41,35], [4,6]
Case 3: Given an input list, split it into n-sized chunks.
Output= [24,54,9], [76,32,42], [97,64,3], [1,93,22], 
Case 1: Split a list in half using Python
In this case, we aim to divide the list into two halves. These halves can be of equal or unequal sizes, depending on the list’s length. Both possibilities will be explored using the slicing technique. Here’s how you can do it:
- Obtain the length of the list using the
- If the length of the parts is not specified, divide the length of the list by 2 using the floor division operator (
//) to determine the middle index of the list.
- Use slicing to create two halves:
Let’s first consider an example where the length of the first half is given.
#create and initialize a list list1 = [1,2,3,4,5,6] #initialize the middle index with the length of first half middle_index=3 #Split the list from starting index upto middle index in first half first_half=list1[:middle_index] #Split the list from middle index index upto the last index in second half sec_half=list1[middle_index:] #printing original lists and two halves print('The original list is: ',list1) print("First half of list is ",first_half) print("Second half of list is ",sec_half)
If the size of the two halves or the splitting index is not specified, you can find the middle index by dividing the length of the list by 2. In cases where the length is odd or the list is asymmetrical, the floor division operator ensures that you obtain a whole number as the middle index.
#function which split the list into two halves def splitlist(inputlist,n): first_half=inputlist[:n] sec_half=inputlist[n:] return first_half,sec_half if __name__ == "__main__" : # create an empty list list1 =  # Take number of elements as input from user length = int(input("Enter number of elements : ")) # iinitialize the list using for loop for i in range(0, length): item = int(input("Enter element "+str(i+1)+" :")) list1.append(item) middle_index=length//2 first,sec=splitlist(list1,middle_index) #printing lists print("Original list: ", list1) print("First half: ", first) print("second half: ", sec)
In the above example, the list consists of an odd number of elements therefore split function returns two unequal lists. As the length of the list is 7, therefore the midpoint is (7/2) = 3.5. The floor operator returns the closest integer value which is less than or equal to a result obtained by division. In this case, the floor operator returns 3 instead of 3.5. Therefore the length of the first half is 3, whereas the other half has a length of 4.
Case 2: Splitting a list into n sublists
Python’s NumPy library provides a built-in function,
array_split(), that can divide a list into n parts. This function takes an array and the number of splits ‘n’ as arguments and returns n subarrays.
import numpy as np #creating a list list1 = [1,2,3,4,5,6,7,8,9] sub_lists = np.array_split(list1, 3) count=1 for i in sub_lists: print("List ", count, ": ",list(i)) count+=1
In this example, we have used the function of the NumPy library which takes the original list and number of splits as an argument and returns the parts of lists.
Case 3: Split list into chunks or n sized parts
If the length of chunks and list is given and you are asked to split the list then you can do this by slicing the operator. The following example shows the implementation of this problem.
def split_list(Input_list, n): for i in range(0, len(Input_list), n): yield Input_list[i:i + n] if __name__ == "__main__" : # create an empty list list1 =  # Take number of elements as input from user length = int(input("Enter number of elements : ")) # iinitialize the list using for loop for i in range(0, length): item = int(input("Enter element "+str(i+1)+" :")) list1.append(item) # Take the size of chunks as an input from user n = int(input("Enter the size of chunks : ")) X=split_list(list1, n) print(list(X))
Alternatively, you can use list comprehension to achieve the same result:
# create an empty list list1 =  # Take number of elements as input from user length = int(input("Enter number of elements : ")) # initialize the list using for loop for i in range(0, length): item = int(input("Enter element "+str(i+1)+" :")) list1.append(item) # Take the size of chunks as an input from user n = int(input("Enter the size of chunks : ")) X = [list1[i:i+n] for i in range(0, length, n)] print("Chunks of Original list are:") for i in X: print(i)
These examples demonstrate how to split a list into chunks or parts of a specified size.
In summary, this tutorial covers three distinct cases for splitting lists in Python, accompanied by detailed explanations and illustrative examples. If you have any questions or need further clarification, please feel free to ask in the comments. Your feedback is highly valued, and we encourage you to explore more Python tutorials.