How can I get the Python unique list from a given list?
For example, I have the following list:
trends = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
And I want the output to be:
['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?
A simple way to get unique values from a list is by converting the list to a set and back to a list, as sets inherently store unique elements.
trends = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
output = list(set(trends))
print(output)
You can use a list comprehension and a set to track the seen elements while maintaining the order.
trends = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
seen = set()
output = [x for x in trends if not (x in seen or seen.add(x))]
print(output)
This dict.fromkeys() method leverages the fact that dictionaries only allow unique keys. It also maintains the order of the list as of Python 3.7+.
trends = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
output = list(dict.fromkeys(trends))
print(output)