duplicate items in a list

Fredrik Lundh fredrik at pythonware.com
Mon Nov 21 06:26:59 EST 2005


Shi Mu wrote:

> I used the following method to remove duplicate items in a list and
> got confused by the error.
>
> >>> a
> [[1, 2], [1, 2], [2, 3]]
> >>> noDups=[ u for u in a if u not in locals()['_[1]'] ]
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> TypeError: iterable argument required

by the way, assuming that it doesn't really matter whether the
resulting list contains lists or tuples, here's a simple oneliner-plus-
optional-import solution:

    # this is only needed if you're using 2.3 or earlier
    >>> from sets import Set as set

    >>> hasDups = [[1, 2], [1, 2], [2, 3]]

    >>> noDups = list(set(map(tuple, hasDups)))

    >>> noDups
    [(1, 2), (2, 3)]

if you need an order-preserving implementation, see raymond's
example over at the cookbook.

</F>






More information about the Python-list mailing list