Question Details

No question body available.

Tags

python python-itertools

Answers (1)

Accepted Answer Available
Accepted Answer
May 21, 2026 Score: 4 Rep: 24,438 Quality: Expert Completeness: 60%

There is some mixing with the type of objects in your current code, and a problem in both versions with your use of the group returned by groupby (your j). It's not a list, but an iterator, so it will be exhausted if you try to use it a second time in a list(j) or such.

We can't use it once to get its length, then a second time to create a list. So, we can either filter by length afterwards, or use the := assignment the first time we iterate on the group to create a list (that is, in the if clause - it gets executed first, before the list can be added to the output)

I would also avoid putting too much in the big list comprehension, and filter the valid filenames before trying to group them (your code would fail if one of the file doesn't have the valid format)

So, you can do:

from itertools import groupby
import re

filelist = [ 'outputAfoobar0.pkl', 'outputAfoobar1.pkl', 'outputAfoobar2.pkl', 'outputAfoobar3.pkl', 'outputBfoobar0.pkl', 'outputBfoobar1.pkl', 'outputBfoobar2.pkl', 'outputBfoobar3.pkl', 'outputGfoobar1.pkl', 'outputHfoobar0.pkl', 'outputHfoobar1.pkl', 'inputAfoobar0.pkl', 'inputHfoobar0.pkl', 'inputHfoobar1.pkl', 'inputHfoobar2.pkl', 'inputHfoobar3.pkl']

we filter the valid filenames *before* trying to group them,

so we can be sure that a valid key will exist

valid
pattern = re.compile(r"output[A-Z]")

we filter with a generator expression, no intermediate list will be created

validnames = (f for f in filelist if validpattern.match(f))

out = [lst for key, grp in groupby(valid
names, key=lambda x: x.split('')[1]) if len(lst:=list(grp))==4]

print(out)

Output:

[['outputAfoobar0.pkl', 
'outputAfoobar1.pkl', 
'outputAfoobar2.pkl', 
'outputAfoobar3.pkl'], 

['output
Bfoobar0.pkl', 'outputBfoobar1.pkl', 'outputBfoobar2.pkl', 'outputBfoobar3.pkl']]

With older versions of Python without the := assignment, you could do for example:

res = (list(grp) for key, grp in groupby(validnames, key=lambda x: x.split('_')[1]))

out = [l for l in res if len(l)==4]