Hi all,
I have a list like this:
[1, 2, 2, 4, 3, 4]
I want to get a new list which has only unique instances of the above list. I want to do this in one line. Is it possible?
The output of the code should be
[1,2,4,3]
The order may change, but I want the list to be uniqued with one line of code.
How would you do it?
Raja Sekharan
How to unique a list in one line?
Started by Raja Sekharan, Dec 01 2008 04:57 AM
5 replies to this topic
#1
Posted 01 December 2008 - 04:57 AM
|
|
|
#2
Posted 01 December 2008 - 07:21 AM
Use set.
>>> old_list = [1, 2, 2, 4, 3, 4] >>> new_list = list(set(old_list)) >>> print old_list, '\n', new_list [1, 2, 2, 4, 3, 4] [1, 2, 3, 4]
#3
Posted 01 December 2008 - 07:25 AM
void, Thanks much
#4
Posted 01 December 2008 - 07:25 AM
You are welcome!
#5
Posted 02 December 2008 - 05:07 PM
I didn't know about set... I'm wondering, is it possible to do something like this?:
I guess it's not but... Anyone knows?
l = [1,2,2,3,4,5,5] new = [i for i in l if i not in __list_being_created__]
I guess it's not but... Anyone knows?
#6
Posted 02 December 2008 - 06:58 PM
manux said:
I didn't know about set... I'm wondering, is it possible to do something like this?:
I guess it's not but... Anyone knows?
l = [1,2,2,3,4,5,5] new = [i for i in l if i not in __list_being_created__]
I guess it's not but... Anyone knows?
I aleady tried that. It throws an exception of an undefined variable. I even instantiated to an empty list using
newlist = []
but the comparison is always done to the empty list so all the list element just get copied to the newlist as it is in the old list(with the duplicates).


Sign In
Create Account


Back to top









