itertools.groupby
itertools.groupby() groups consecutive elements that share a key. Data must be sorted by the key first.
itertools.groupby() groups consecutive elements that share a key. Data must be sorted by the key first.
from itertools import groupby
data = [("A", 1), ("A", 2), ("B", 3), ("B", 4)]
for key, group in groupby(data, key=lambda x: x[0]):
print(key, list(group))
Sort by the same key before groupby — it only groups consecutive runs.