If your data is already sorted by the file name, you can use itertools.groupby:

files = ['001_1.png', '001_2.png', '001_3.png', '002_1.png','002_2.png',
        '003_1.png', '003_2.png', '003_3.png']

import itertools

keyfunc = lambda filename: filename[:3]

# this creates an iterator that yields `(group, filenames)` tuples,
# but `filenames` is another iterator
grouper = itertools.groupby(files, keyfunc)

# to get the result as a nested list, we iterate over the grouper to
# discard the groups and turn the `filenames` iterators into lists
result = [list(files) for _, files in grouper]

print(list(result))
# [['001_1.png', '001_2.png', '001_3.png'],
#  ['002_1.png', '002_2.png'],
#  ['003_1.png', '003_2.png', '003_3.png']]

Otherwise, you can base your code on this recipe, which is more efficient than sorting the list and then using groupby.

  • Input: Your input is a flat list, so use a regular ol' loop to iterate over it:

    for filename in files:
    
  • Group identifier: The files are grouped by the first 3 letters:

    group = filename[:3]
    
  • Output: The output should be a nested list rather than a dict, which can be done with

    result = list(groupdict.values())
    

Putting it together:

files = ['001_1.png', '001_2.png', '001_3.png', '002_1.png','002_2.png',
        '003_1.png', '003_2.png', '003_3.png']

import collections

groupdict = collections.defaultdict(list)
for filename in files:
    group = filename[:3]
    groupdict[group].append(filename)

result = list(groupdict.values())

print(result)
# [['001_1.png', '001_2.png', '001_3.png'],
#  ['002_1.png', '002_2.png'],
#  ['003_1.png', '003_2.png', '003_3.png']]

Read the recipe answer for more details.

Answer from Aran-Fey on Stack Overflow
Top answer
1 of 6
6

If your data is already sorted by the file name, you can use itertools.groupby:

files = ['001_1.png', '001_2.png', '001_3.png', '002_1.png','002_2.png',
        '003_1.png', '003_2.png', '003_3.png']

import itertools

keyfunc = lambda filename: filename[:3]

# this creates an iterator that yields `(group, filenames)` tuples,
# but `filenames` is another iterator
grouper = itertools.groupby(files, keyfunc)

# to get the result as a nested list, we iterate over the grouper to
# discard the groups and turn the `filenames` iterators into lists
result = [list(files) for _, files in grouper]

print(list(result))
# [['001_1.png', '001_2.png', '001_3.png'],
#  ['002_1.png', '002_2.png'],
#  ['003_1.png', '003_2.png', '003_3.png']]

Otherwise, you can base your code on this recipe, which is more efficient than sorting the list and then using groupby.

  • Input: Your input is a flat list, so use a regular ol' loop to iterate over it:

    for filename in files:
    
  • Group identifier: The files are grouped by the first 3 letters:

    group = filename[:3]
    
  • Output: The output should be a nested list rather than a dict, which can be done with

    result = list(groupdict.values())
    

Putting it together:

files = ['001_1.png', '001_2.png', '001_3.png', '002_1.png','002_2.png',
        '003_1.png', '003_2.png', '003_3.png']

import collections

groupdict = collections.defaultdict(list)
for filename in files:
    group = filename[:3]
    groupdict[group].append(filename)

result = list(groupdict.values())

print(result)
# [['001_1.png', '001_2.png', '001_3.png'],
#  ['002_1.png', '002_2.png'],
#  ['003_1.png', '003_2.png', '003_3.png']]

Read the recipe answer for more details.

2 of 6
4

Something like that should work:

import itertools


mylist = [...]
[list(v) for k,v in itertools.groupby(mylist, key=lambda x: x[:3])]

If input list isn't sorted, than use something like that:

import itertools


mylist = [...]
keyfunc = lambda x:x[:3]
mylist = sorted(mylist, key=keyfunc)
[list(v) for k,v in itertools.groupby(mylist, key=keyfunc)]
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_split.asp
NumPy Splitting Array
Use the array_split() method, pass in the array you want to split and the number of splits you want to do.
🌐
Mdjubayerhossain
mdjubayerhossain.com › numpy › notebooks › 08_SplittingArrays.html
Splitting Arrays — Introduction to NumPy
Split an array into multiple sub-arrays. By specifying the number of equally shaped arrays to return, or by specifying the columns after which the division should occur ... --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ...
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-131.php
Python NumPy: Split a given array into multiple sub-arrays vertically - w3resource
August 29, 2025 - Original arrays: [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.] [ 8. 9. 10. 11.] [12. 13. 14. 15.]] Split an array into multiple sub-arrays vertically: [array([[0., 1., 2., 3.], [4., 5., 6., 7.]]), array([[ 8., 9., 10., 11.], [12., 13., 14., 15.]])]
🌐
Educative
educative.io › answers › what-is-the-array-split-method-in-numpy
What is the array split() method in Numpy?
The numpy.array_split() method in Python is used to split an array into multiple sub-arrays of equal size.
🌐
Kanoki
kanoki.org › 2020 › 06 › 11 › how-to-split-numpy-arrays
How to split Numpy Arrays | kanoki
June 11, 2020 - array_split(): It Split an array into multiple sub-arrays of equal or near-equal size.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › how to split numpy array | using split()
How to Split NumPy Array | Using split() - Spark By {Examples}
March 27, 2024 - How to split an array into multiple arrays in Numpy? In NumPy, the numpy.split() function can be used to split an array into more than one (multiple) sub
Find elsewhere
🌐
Vultr Docs
docs.vultr.com › python › third-party › numpy › split
Python Numpy split() - Divide Array | Vultr Docs
January 1, 2025 - The split() function in the NumPy library is a versatile tool for dividing an array into multiple sub-arrays. Whether working with large datasets or performing parallel computations, this function allows for efficient data manipulation by segmenting ...
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-132.php
Python NumPy: Split array into multiple sub-arrays along the 3rd axis - w3resource
August 29, 2025 - Original arrays: [[[ 0. 1. 2. 3.] [ 4. 5. 6. 7.]] [[ 8. 9. 10. 11.] [12. 13. 14. 15.]]] split array into multiple sub-arrays along the 3rd axis: [array([[[ 0., 1.], [ 4., 5.]], [[ 8., 9.], [12., 13.]]]), array([[[ 2., 3.], [ 6., 7.]], [[10., 11.], [14., 15.]]])]
Top answer
1 of 3
7

Approach #1

Using NumPy's numpy.split to have list of arrays as output -

import numpy as np

arr = np.array(a) # a is input list
out = np.split(arr,np.flatnonzero(arr[1:] < arr[:-1])+1)

Approach #2

Using loop comrehension to split the list directly and thus avoid numpy.split for efficiency purposes -

idx = np.r_[0, np.flatnonzero(np.diff(a)<0)+1, len(a)]
out = [a[idx[i]:idx[i+1]] for i in range(len(idx)-1)]

Output for given sample -

In [52]: idx = np.r_[0, np.flatnonzero(np.diff(a)<0)+1, len(a)]

In [53]: [a[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
Out[53]: 
[[100, 564, 572, 578, 584, 590, 596, 602, 608, 614, 620, 625, 631],
 [70, 119, 125, 130, 134, 139, 144, 149, 154, 159, 614, 669],
 [100, 136, 144, 149, 153, 158, 163, 167, 173, 179],
 [62, 72, 78, 82, 87, 92, 97, 100, 107, 112, 117, 124, 426],
 [100, 129, 135, 140, 145, 151]]

We are using np.diff here, which feeds in a list in this case and then computes the differentiation. So, a better alternative would be with converting to array and then using comparison between shifted slices of it instead of actually computing the differentiation values. Thus, we could get idx like this as well -

arr = np.asarray(a)
idx = np.r_[0, np.flatnonzero(arr[1:] < arr[:-1])+1, len(arr)]

Let's time it and see if there's any improvement -

In [84]: a = np.random.randint(0,100,(1000,100)).cumsum(1).ravel().tolist()

In [85]: %timeit np.r_[0, np.flatnonzero(np.diff(a)<0)+1, len(a)]
100 loops, best of 3: 3.24 ms per loop

In [86]: arr = np.asarray(a)

In [87]: %timeit np.asarray(a)
100 loops, best of 3: 3.05 ms per loop

In [88]: %timeit np.r_[0, np.flatnonzero(arr[1:] < arr[:-1])+1, len(arr)]
10000 loops, best of 3: 77 µs per loop

In [89]: 3.05+0.077
Out[89]: 3.127

So, a marginal improvement there with the shifting and comparing method with the conversion : np.asarray(a) eating-up most of the runtime.

2 of 3
4

I know you tagged numpy. But here's a implementation without any dependencies too:

lst = [100, 564, 572, 578, 584, 590, 596, 602, 608, 614, 620, 625, 631, 70, 119, 
125, 130, 134, 139, 144, 149, 154, 159, 614, 669, 100, 136, 144, 149, 153, 
158, 163, 167, 173, 179, 62, 72, 78, 82, 87, 92, 97, 100, 107, 112, 117, 
124, 426, 100, 129, 135, 140, 145, 151]

def split(lst):
  last_pos = 0
  for i in range(1, len(lst)):
    if lst[i] < lst[i-1]:
      yield lst[last_pos:i]
      last_pos = i
  if(last_pos <= len(lst)-1):
    yield lst[last_pos:]

print([x for x in split(lst)])
🌐
GeeksforGeeks
geeksforgeeks.org › python › splitting-arrays-in-numpy
Splitting Arrays in NumPy - GeeksforGeeks
December 23, 2025 - DSA Python · Data Science · NumPy · Pandas · Practice · Django · Flask · Last Updated : 23 Dec, 2025 · Splitting arrays means dividing a single NumPy array into multiple smaller sub-arrays. NumPy provides several functions that make this easy by allowing you to split arrays along different directions (rows, columns, depth).
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-61.php
NumPy: Split an array of 14 elements into 3 arrays - w3resource
print(np.split(x, [2, 6])): The np.split() function is used to split the array x into multiple subarrays.
Author: array-split
🌐
w3resource
w3resource.com › numpy › manipulation › split.php
NumPy: numpy.split() function - w3resource
April 24, 2026 - The numpy.split() function is used to split an array into multiple sub-arrays.
🌐
PyPI
pypi.org › project › array-split
array-split · PyPI
Arbitrary start index for the shape to be partitioned. Maximum number of bytes for a sub-array with constraints: sub-arrays are an even multiple of a specified sub-tile shape ... >>> from array_split import array_split, shape_split >>> import numpy as np >>> >>> ary = np.arange(0, 4*9) >>> >>> array_split(ary, 4) # 1D split into 4 sections (like numpy.array_split) [array([0, 1, 2, 3, 4, 5, 6, 7, 8]), array([ 9, 10, 11, 12, 13, 14, 15, 16, 17]), array([18, 19, 20, 21, 22, 23, 24, 25, 26]), array([27, 28, 29, 30, 31, 32, 33, 34, 35])] >>> >>> shape_split(ary.shape, 4) # 1D split into 4 parts, re
      » pip install array-split
    
Published: Aug 04, 2024
Version: 0.6.5
🌐
Programiz
programiz.com › python-programming › numpy › methods › split
NumPy split()
Online Python Online JavaScript Online SQL Online Java Online HTML Online C Online C++ Online C# Online PHP Online Swift Online Kotlin Online TypeScript Online Go Online Rust Online Scala Online Dart Online R Online Ruby ... The NumPy split() method splits an array into multiple sub-arrays.
🌐
DataCamp
datacamp.com › doc › numpy › split
NumPy split()
The `split()` function in NumPy is used to divide an array into multiple sub-arrays.