Is there a way to make a list comprehension in Python that only contains unique items?
My original idea was to use something like this :
new_items = [unicode(item) for item in items]
However, I later realized that I needed to omit duplicate items. So I ended up with this ugly monstrosity :
unique_items = []
for item in items :
unicode_item = unicode(item)
if unicode_item not in unique_items :
unique_items.append(unicode_item)
Now this is far less pretty (and readable) than a simple list comprehension. So, is there a way to make a list comprehension equivalent to the above code?
Also order does matter, so I can't just use a set comprehension.
Make it a helper function, like so.
outputs
Your original idea works with a set comprehension:
I short one liner might be:
Well, there is no ordered set, but we can misuse OrderedDict:
Gives: