ActiveState Code

Recipe 440509: Remove Duplicacy from a Python List


I needed a list for a long bunch of elements but then I didn't want duplicates. I LOVE Sets, so I use a set to get the list I needed.

Python
1
2
from set import Set 
list = Set(list).elems

Discussion

Thanks.

Modified for brevity!

Comments

  1. 1. At 7:45 a.m. on 2 sep 2005, Nick Matsakis said:

    This could be much shorter, and really doesn't need to be a function:

    from sets import Set
    new_list = list(Set(old_list))
    

    This won't preserve the order of the original list, of course.

  2. 2. At 7:59 a.m. on 2 sep 2005, Bibha Tripathi (the author) said:

    Thanks Nick. But is the list object callable?

    I get the following when I run the above:

    >>> new_list = list(Set(old_list))
    Traceback (most recent call last):
      File "", line 1, in ?
    TypeError: 'list' object is not callable
    
  3. 3. At 8:35 a.m. on 2 sep 2005, Bill Mill said:

    Don't redefine the list() built-in. >>> from sets import Set

    >>> old_list = [1,2,3,3,4,4,4,5]
    
    
    
    >>> new_list = list(Set(old_list))
    
    
    
    >>> list = []
    
    
    
    >>> new_list = list(Set(old_list))
    

    Traceback (most recent call last):

    File "", line 1, in ?

    TypeError: 'list' object is not callable

  4. 4. At 6:31 a.m. on 5 sep 2005, Michael Watkins said:

    And as of 2.4... Even simpler, and faster, as of Python 2.4 with the C implementation of set data type in the core:

    ->> L = [1,1,1,2,3,1,5,6,7] ->> list(set(L)) [1, 2, 3, 5, 6, 7]

  5. 5. At 6:56 a.m. on 5 sep 2005, Michael Watkins said:

    Mike Watkins: oops, left result out.

    ->> L = [1,1,1,2,3,1,5,6,7]

    ->> list(set(L))

    [1, 2, 3, 5, 6, 7]

  6. 6. At 9:17 a.m. on 28 oct 2005, Angelo Probst said:

    For versions later 2.3. a = [1, 2, 2, 3, 4, 4, 5] b = {} for i in a: b[i] = 0 a = b.keys()

  7. 7. At 9:21 a.m. on 28 oct 2005, Angelo Probst said:
    a = [1, 2, 2, 3, 4, 4, 5]
    
    
    
    b = {}
    
    
    
    for i in a: b[i] = 0
    
    
    
    a = b.keys()
    

Sign in to comment