[Tutor] Eliminating consecutive duplicates in a list

Kent Johnson kent37 at tds.net
Thu Jun 18 21:45:33 CEST 2009


On Thu, Jun 18, 2009 at 9:15 AM, karma<dorjetarap at googlemail.com> wrote:
> I was playing around with eliminating duplicates in a list not using
> groupby. From the two solutions below, which is more "pythonic".
> Alternative solutions would be welcome.

But why not use groupby()? That seems much clearer to me:

In [1]: from itertools import groupby

In [3]: x=[1,1,1,3,2,2,2,2,4,4]

In [4]: [ k for k, v in groupby(x) ]
Out[4]: [1, 3, 2, 4]

In [5]: x=[1,1,1,3,2,2,2,4,4,2,2]

In [6]: [ k for k, v in groupby(x) ]
Out[6]: [1, 3, 2, 4, 2]

Kent


More information about the Tutor mailing list