The itertools.groupby() function is a convenient way to group adjacent duplicate items of an iterable.
For instance, we can group a long string as follows:
from itertools import groupby
for key, group in groupby('YAaANNGGG'):
print(key, list(group))
# Y ['Y']
# A ['A']
# a ['a']
# A ['A']
# N ['N', 'N']
# G ['G', 'G', 'G']
Furthermore, we can harness its second argument to tell the groupby() function how to determine whether two items are the same or not:
from itertools import groupby
for key, group in groupby('YAaANNGGG', lambda x: x.upper()):
print(key, list(group))
# Y ['Y']
# A ['A', 'a', 'A']
# N ['N', 'N']
# G ['G', 'G', 'G']