Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get unique values from a list in python [duplicate]

Tags:

python

list

I want to get the unique values from the following list:

['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow'] 

The output which I require is:

['nowplaying', 'PBS', 'job', 'debate', 'thenandnow'] 

This code works:

output = [] for x in trends:     if x not in output:         output.append(x) print(output) 

is there a better solution I should use?

like image 323
savitha Avatar asked Oct 15 '12 14:10

savitha


People also ask

What does unique () do in Python?

unique() function. The unique() function is used to find the unique elements of an array. Returns the sorted unique elements of an array.


1 Answers

First declare your list properly, separated by commas. You can get the unique values by converting the list to a set.

mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow'] myset = set(mylist) print(myset) 

If you use it further as a list, you should convert it back to a list by doing:

mynewlist = list(myset) 

Another possibility, probably faster would be to use a set from the beginning, instead of a list. Then your code should be:

output = set() for x in trends:     output.add(x) print(output) 

As it has been pointed out, sets do not maintain the original order. If you need that, you should look for an ordered set implementation (see this question for more).

like image 191
lefterav Avatar answered Sep 22 '22 06:09

lefterav