Does Python have a method similar to Haskell's group?

What I am looking for is a method that will group common elements together like so:

foo([1,2,2,3,3,3,1,1]) = [[1], [2,2], [3,3,3], [1,1]]

Does Python have a built in method which can do something like this or would I have to implement this myself?

5 comments · 100% upvoted · other discussions

comments

novel_yet_trivial

Reread your question ... you want itertools.groupby():

>>> from itertools import groupby
>>> [list(g) for k,g in groupby([1,2,2,3,3,3,1,1])]
[[1], [2, 2], [3, 3, 3], [1, 1]]
shaggorama

Good ol' itertools

vgbm [OP]

This is exactly what I needed, thanks :)

commandlineluser

http://docs.python.org/3/library/itertools.html#itertools.groupby

>>> import itertools
>>> [ list(v) for k, v in itertools.groupby([1,2,2,3,3,3,1,1]) ]
[[1], [2, 2], [3, 3, 3], [1, 1]]
novel_yet_trivial

How about collections.Counter()?