Skip to content

Instantly share code, notes, and snippets.

@phrz
Created June 12, 2025 15:16
Show Gist options
  • Save phrz/a70b0c2e4b2eea74ce5faa14931c7159 to your computer and use it in GitHub Desktop.
Save phrz/a70b0c2e4b2eea74ce5faa14931c7159 to your computer and use it in GitHub Desktop.
Splits lists on separator elements with custom comparator function
def chunk_on(l, sep, test=lambda a, b: a == b, include_sep=False, skip_empty=True):
'''for list `l`, yield slices that represent each run of the list between `sep`s.'''
start = 0
end = 0
for i in range(len(l)):
if test(l[i], sep):
end = i
if include_sep and i < len(l) - 1:
end += 1
if (skip_empty and start != end) or not skip_empty:
yield l[start:end]
start = end + 1
if l[-1] != sep:
yield l[start:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment