How to split a list in half using Python

In this tutorial, We will learn about how to Split a List in Half using Python Programming. Lists are the mutable data types that are able to store a collection of items. This article discusses different ways to split the list in half, n sublists, n parts, and chunks. The two halves of the original list contain elements in the same order as in the original. Moreover, we will also discuss

If you want to learn more about lists in python, See Python List Tutorials

  • Case 1: Split a list in Half
  • Case 2: Split a list into n sublists or parts
  • Case 3: Split a list into chunks
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]

Case 1: split a list in half using python

The first case is to split the list into half or two halves. These halves can be of equal size or unequal depending upon the length of the list. Both possibilities will be discussed here. We can use the slicing technique to divide the list. This can be done using the following steps:

  • Get the length of a list using len() function
  • If the length of the parts is not given, then divide the length of list by 2 using floor operator to get the middle index of the list
  • Slice the list into two halves using [:middle_index] and [middle_index:]

Example

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

split list into half

What if the size of two halves or splitting index is not given. Then we have to find the middle index of the list which can be done by dividing the length of the list by 2. if But if the length of the list is an odd number or the list is unsymmetrical then on dividing, we will get a float value. Therefore, we’ll use floor operator(//) which rounds the result.

Example:

#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:

split list in half

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 has a NumPy library which has a built-in function ‘array_split()’ that can divide the list into n parts. The function takes an array and the number of splits ‘n’ as an argument and returns lists of n subarrays. Let’s understand the use of this function using an example.

Example:

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:

splits lists into n sublists

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.

Example:

 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:

split list into chunks

The same problem can also be done using list comprehension.

# 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:

n parts splitting

This tutorial discussed three different cases of splitting lists in detail along with examples. If you have any queries regarding this article, please let us know in the comments. Your feedback would be highly appreciated.

See more Python Tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *