In this article, we will see how to split a list into multiple sub-lists.

Python lists are non-homogeneous and used to store multiple values of different data types which can be either numeric, Boolean, characters, etc under the same name.

Following is an example of how to separate a list into multiple sub-lists.

def listSplit(srcList, subLists=1):
    length = len(srcList)
    return [ srcList[i*length // subLists: (i+1)*length // subLists] 
             for i in range(subLists) ]

# Create a list
A = [0,1,2,3,4,5,6,7,8,9]

print(listSplit(A, subLists=1))
print(listSplit(A, subLists=3))
print(listSplit(A, subLists=8))

Explanation:

  • listSplit accepts two parameters, i.e. original list and no of sublists you would like to create.
  • Get the length of the list that you want to divide.
  • For example, if the length of the list is 6 and the sublist size is 3, then the first sublist will be in the range of 0 to 2, and the second sublist will be in the range of 3 to 5, and so on...