[Tutor] Eliminating consecutive duplicates in a list

Dave Angel davea at ieee.org
Thu Jun 18 18:34:17 CEST 2009


karma 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.
>
> Thanks
>
> x=[1,1,1,3,2,2,2,2,4,4]
>
> [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0]
>
> [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]]
>
> output:
> [1, 3, 2, 4]
>
>   
I'd vote for the first form, though I might make a generator out of it.

gen = (v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0)
print list(gen)

Of course, that depends on the lifetime of the various objects.  
Interestingly, if you modify x after defining gen, but before using it, 
gen will use the new contents of x.



More information about the Tutor mailing list