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.
THE FOLLOWING CASES WILL BE DISCUSSED IN THIS ARTICLE:
Case 1: Given an input list, split it into two halves.
(a) When the list is symmetrical.
Example:
Input= [1,7,5,3,2,8,9,4]
Output= [1,7,5,3] and [2,8,9,4]
(b) When the list is asymmetrical.
Example:
Input= [13,6,2,4,4,81,9,32,5,7,11]
Output= [13,6,2,4,4] and [81,9,32,5,7,11]
Case 2: Given an input list, split it into n sublists.
Example:
n=4
Input= [5,3,2,1,3,24,5,41,35,4,6]
Output= [5,3,2], [1,3,24], [5,41,35], [4,6]
Case 3: Given an input list, split it into n-sized chunks.
Example:
n=3
Input= [24,54,9,76,32,42,97,64,3,1,93,22,53]
Output= [24,54,9], [76,32,42], [97,64,3], [1,93,22], [53]
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
len()
function. - 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:
[:middle_index]
and[middle_index:
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)
OUTPUT:
The original list is: [1, 2, 3, 4, 5, 6]
First half of list is [1, 2, 3]
Second half of list is [4, 5, 6]
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)
OUTPUT:
Enter number of elements : 7
Enter element 1 :6
Enter element 2 :2
Enter element 3 :6
Enter element 4 :4
Enter element 5 :0
Enter element 6 :2
Enter element 7 :4
Original list: [6, 2, 6, 4, 0, 2, 4]
First half: [6, 2, 6]
second half: [4, 0, 2, 4]
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.
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
OUTPUT:
List 1 : [1, 2, 3]
List 2 : [4, 5, 6]
List 3 : [7, 8, 9]
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.
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))
OUTPUT:
Enter number of elements : 6
Enter element 1 :8
Enter element 2 :1
Enter element 3 :3
Enter element 4 :2
Enter element 5 :4
Enter element 6 :2
Enter the size of chunks : 2
[[8, 1], [3, 2], [4, 2]]
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)
OUTPUT:
Enter number of elements : 6
Enter element 1 :2
Enter element 2 :4
Enter element 3 :5
Enter element 4 :4
Enter element 5 :2
Enter element 6 :3
Enter the size of chunks : 3
Chunks of Original list are:
[2, 4, 5]
[4, 2, 3]
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.