# Python – Split List on next larger value

PythonServer Side ProgrammingProgramming

When it is required to split a list based on the next larger value, a list comprehension, the ‘iter’ method and the ‘islice’ methods are used.

## Example

Below is a demonstration of the same −

from itertools import islice

my_list = [11, 22, 33, 34, 45, 26, 87,11]
print("The list is :")
print(my_list)

length_to_split = [2, 5, 3]
print("The split length list is :")
print(length_to_split)

temp = iter(my_list)
my_result = [list(islice(temp, element)) for element in length_to_split]

print("The result is :")
print(my_result)

## Output

The list is :
[11, 22, 33, 34, 45, 26, 87, 11]
The split length list is :
[2, 5, 3]
The result is :
[[11, 22], [33, 34, 45, 26, 87], [11]]

## Explanation

• The required packages are imported into the environment.

• A list of integers is defined and is displayed on the console.

• Another list of integers is defined and is displayed on the console.

• The ‘iter’ method is called on the list, and assigned to a variable.

• A list comprehension is used to iterate over the elements, and the ‘islice’ method is used.

• This is converted to a list and is assigned to a variable.

• This is the output that is displayed on the console.

Published on 08-Sep-2021 08:27:19