Removing duplicates from a list

Rubinho robin.cull at gmail.com
Wed Sep 14 09:42:58 EDT 2005


Peter Otten wrote:
> Rubinho wrote:
>
> > I've a list with duplicate members and I need to make each entry
> > unique.
> >
> > I've come up with two ways of doing it and I'd like some input on what
> > would be considered more pythonic (or at least best practice).
> >
> > Method 1 (the traditional approach)
> >
> > for x in mylist:
> >     if mylist.count(x) > 1:
> >         mylist.remove(x)
>
> That would be an odd tradition:

By tradition I wasn't really talking Python tradition; what I meant was
that the above pattern is similar to what would be generated by people
used to traditional programming languages.

>
> >>> mylist = [1, 2, 1, 3, 2, 3]
> >>> for x in mylist:
> ...     if mylist.count(x) > 1:
> ...             mylist.remove(x)
> ...
> >>> mylist
> [2, 1, 2, 3] # oops!

But you're absolutely right, it doesn't work! Oops indeed :)

I've gone with Thomas's suggestion above of: mylist=list(set(mylist))

Thanks, 

Robin




More information about the Python-list mailing list