Python – Split List on next larger value

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. This technique allows you to divide a list into chunks of specified sizes sequentially.

Basic Example

Below is a demonstration of splitting a list into chunks of different sizes ?

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)
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]]

How It Works

The solution uses these key components:

  • iter() ? Creates an iterator from the original list

  • islice() ? Extracts a specified number of elements from the iterator

  • List comprehension ? Applies islice for each chunk size and creates sublists

Alternative Approach Using Manual Slicing

You can also split a list using traditional slicing with index tracking ?

def split_list_by_sizes(data, sizes):
    result = []
    start = 0
    
    for size in sizes:
        end = start + size
        result.append(data[start:end])
        start = end
    
    return result

my_list = [10, 20, 30, 40, 50, 60, 70, 80]
split_sizes = [3, 2, 3]

result = split_list_by_sizes(my_list, split_sizes)
print("Original list:", my_list)
print("Split sizes:", split_sizes)
print("Result:", result)
Original list: [10, 20, 30, 40, 50, 60, 70, 80]
Split sizes: [3, 2, 3]
Result: [[10, 20, 30], [40, 50], [60, 70, 80]]

Comparison

Method Memory Usage Readability Best For
islice() with iter() Memory efficient Concise Large lists
Manual slicing Creates sublists More explicit Simple cases

Conclusion

The islice() method with iter() provides an efficient way to split lists into chunks of varying sizes. Use manual slicing for simpler cases where memory efficiency is not a primary concern.

Updated on: 2026-03-26T01:16:57+05:30

229 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements