Custom list split in Python

PythonServer Side ProgrammingProgramming

Data analytics throws complex scenarios where the data need to be wrangled to moved around. In this context let’s see how we can take a big list and split it into many sublists as per the requirement. In this article we will explore the approaches to achieve this.

With zip and for loop

In this approach we use list dicing to get the elements from the point at which the splitting has to happen. Then we use zip and for loop to create the sublists using a for loop.

Example

 Live Demo

Alist = ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]

# The indexes to split at
split_points = [2, 5, 8]

# Given list
print("Given list : " + str(Alist))

# SPlit at
print("The points of splitting : ",split_points)

#Perform the split
split_list = [Alist[i: j] for i, j in zip([0] +
split_points, split_points + [None])]

# printing result
print("The split lists are : ", split_list)

Output

Running the above code gives us the following result −

Given list : ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]
The points of splitting : [2, 5, 8]
The split lists are : [['Mon', 'Tue'], ['Wed', 6, 7], ['Thu', 'Fri', 11], [21, 4]]

Using chain and zip

The chain function makes an iterator that returns elements from the first iterable until it is exhausted. So it marks the points where the splitting happens. Then we use the zip function to package the result of splitting into sublists.

Example

 Live Demo

from itertools import chain
Alist = ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]

# The indexes to split at
split_points = [2, 5, 8]

# Given list
print("Given list : ", str(Alist))

# Split at
print("The points of splitting : ",split_points)

# to perform custom list split
sublists = zip(chain([0], split_points), chain(split_points, [None]))
split_list = list(Alist[i : j] for i, j in sublists)

# printing result
print("The split lists are : ", split_list)

Output

Running the above code gives us the following result −

Given list : ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]
The points of splitting : [2, 5, 8]
The split lists are : [['Mon', 'Tue'], ['Wed', 6, 7], ['Thu', 'Fri', 11], [21, 4]]
raja
Published on 04-May-2020 12:59:25
Advertisements