Jump to content

How to unique a list in one line?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
Raja Sekharan

Raja Sekharan

    Newbie

  • Members
  • PipPip
  • 13 posts
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

#2
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
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
Raja Sekharan

Raja Sekharan

    Newbie

  • Members
  • PipPip
  • 13 posts
void, Thanks much

#4
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
You are welcome!

#5
manux

manux

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 234 posts
I didn't know about set... I'm wondering, is it possible to do something like this?:
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
Raja Sekharan

Raja Sekharan

    Newbie

  • Members
  • PipPip
  • 13 posts

manux said:

I didn't know about set... I'm wondering, is it possible to do something like this?:
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).