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?
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).