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.
1 2 | from set import Set
list = Set(list).elems
|
Thanks.
Modified for brevity!
Tags: shortcuts
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.
1 2 | from set import Set
list = Set(list).elems
|
Thanks.
Modified for brevity!
This could be much shorter, and really doesn't need to be a function:
This won't preserve the order of the original list, of course.
Thanks Nick. But is the list object callable?
I get the following when I run the above:
Don't redefine the list() built-in. >>> from sets import Set
Traceback (most recent call last):
File "", line 1, in ?
TypeError: 'list' object is not callable
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]
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]
For versions later 2.3. a = [1, 2, 2, 3, 4, 4, 5] b = {} for i in a: b[i] = 0 a = b.keys()