Welcome, guest | Sign In | My Account | Store | Cart

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, 2 lines
1
2
from set import Set 
list = Set(list).elems

Thanks.

Modified for brevity!

7 comments

Nick Matsakis 18 years, 7 months ago  # | flag

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.

Bibha Tripathi (author) 18 years, 7 months ago  # | flag

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
Bill Mill 18 years, 7 months ago  # | flag

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

Michael Watkins 18 years, 7 months ago  # | flag

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]

Michael Watkins 18 years, 7 months ago  # | flag

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]

Angelo Probst 18 years, 5 months ago  # | flag

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

Angelo Probst 18 years, 5 months ago  # | flag
a = [1, 2, 2, 3, 4, 4, 5]



b = {}



for i in a: b[i] = 0



a = b.keys()
Created by Bibha Tripathi on Fri, 2 Sep 2005 (PSF)
Python recipes (4591)
Bibha Tripathi's recipes (4)

Required Modules

Other Information and Tasks