Use collections.defaultdict(list)
:
from collections import defaultdict
lst = [("a",4), ("b",4), ("a",5), ("b",3)]
result = defaultdict(list)
for a, b in lst:
result[a].append(b)
print sorted(result.items())
# prints: [('a', [4, 5]), ('b', [4, 3])]
Before the sort the algorithm has O(n)
complexity; the group by algorithm has O(n * log(n))
and the set/list/dict comprehension has something greater than O(n^2)