get rid of duplicate elements in list without set

Peter Otten __peter__ at web.de
Fri Mar 20 18:36:01 CET 2009


Alexzive wrote:

> I'd like to get the same result of set() but getting an indexable
> object.
> How to get this in an efficient way?
> 
> Example using set
> 
> A = [1, 2, 2 ,2 , 3 ,4]
> B= set(A)
> B = ([1, 2, 3, 4])
> 
>  B[2]
> TypeError: unindexable object

If the initial list is ordered or at least equal items are neighbours you
can use groubpy():

>>> from itertools import groupby
>>> a = [1,1,1,2,2,3,4,4,4]
>>> [key for key, group in groupby(a)]
[1, 2, 3, 4]

Here's what happens if there are equal items that are not neigbours:

>>> b = [1,1,1,2,2,2,3,3,2,1,1,1,1]
>>> [key for key, group in groupby(b)]
[1, 2, 3, 2, 1]

Peter



More information about the Python-list mailing list