This question already has an answer here:
- Removing duplicates in lists 43 answers
I want to get the unique values from the following list:
[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
The output which I require is:
[u'nowplaying', u'PBS', u'job', u'debate', u'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?
This is simple solution-
set
can help you filter out the elements from the list that are duplicates. It will work well forstr
,int
ortuple
elements, but if your list containsdict
or otherlist
elements, then you will end up withTypeError
exceptions.Here is a general order-preserving solution to handle some (not all) non-hashable types:
For long arrays
If you want to get unique elements from a list and keep their original order, then you may employ
OrderedDict
data structure from Python's standard library:In fact, if you are using Python ≥ 3.6, you can use plain
dict
for that:It's become possible after the introduction of "compact" representation of dicts. Check it out here. Though this "considered an implementation detail and should not be relied upon".
Same order unique list using only a list compression.
enumerates
gives the indexi
and elemente
as atuple
.my_list.index
returns the first index ofe
. If the first index isn'ti
then the current iteration'se
is not the firste
in the list.Edit
I should note that this isn't a good way to do it, performance-wise. This is just a way that achieves it using only a list compression.
By using basic property of Python Dictionary:
Output will be: