Use groupby from the itertools module.
from itertools import groupby L = [2, 2, 3, 4, 4, 10] L.sort() for key, iterator in groupby(L): print key, list(iterator)
Result:
2 [2, 2]
3 [3]
4 [4, 4]
10 [10]
A few things you need to know about: groupby needs the data that it works to be sorted by the same key that you want to group, or it will not work. In addition, the iterator must be consumed before moving on to the next group, so make sure you store list(iterator) in another list or something like that. One-liner gives you the result you want:
>>> [list(it) for key, it in groupby(sorted(L))] [[2, 2], [3], [4, 4], [10]]
source share