>>> import itertools >>> [(k, len(list(g))) for k, g in itertools.groupby(l)] [(4, 4), (5, 3), (6, 1), (7, 3)]
This preserves the order of the elements, and also allows you to repeat the elements:
>>> l=[4,4,4,4,5,5,5,6,7,7,7,4,4,4,4,4] >>> [(k, len(list(g))) for k, g in itertools.groupby(l)] [(4, 4), (5, 3), (6, 1), (7, 3), (4, 5)]