Skip to content

Instantly share code, notes, and snippets.

@nathan-cruz77
Last active December 13, 2023 02:48
Show Gist options
  • Save nathan-cruz77/97efd4856dfafc4359b032fa65148af3 to your computer and use it in GitHub Desktop.
Save nathan-cruz77/97efd4856dfafc4359b032fa65148af3 to your computer and use it in GitHub Desktop.
Group consecutive equal items of iterable
# Group equal consecutive items of iterable.
#
#
# Sample usage:
#
# >>> group_equal('aaabbcd')
# [['a', 'a', 'a'], ['b', 'b'], ['c'], ['d']]
#
def group_equal(iterable):
subgroups = []
g = []
for item in iterable:
if not g or item == g[0]:
g.append(item)
else:
subgroups.append(g)
g = [item]
if g:
subgroups.append(g)
return subgroups
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment