You can use itertools.groupby:
>>> import itertools
>>> [key for key, grp in itertools.groupby([1, 2, 2, 3])]
[1, 2, 3]
itertools.groupby
returns an iterator. By iterating it, you will get a key, group pairs. (key
will be a item if no key
function is specified, otherwise the return value of the key
function). group
is an iterator which will yields items grouped by applying key
function (if not specified, same values will be grouped)
>>> import itertools
>>> it = itertools.groupby([1, 2, 2, 3])
>>> it
>>> for key, grp in it:
... print(key)
... print(grp)
...
1
2
3
>>> it = itertools.groupby([1, 2, 2, 3])
>>> for key, grp in it:
... print(list(grp))
...
[1]
[2, 2]
[3]
Above solution, I used only key
because the question does not care how many items are adjacent.