Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best / most pythonic way to get an ordered list of unique items

Tags:

python

list

I have one or more unordered sequences of (immutable, hashable) objects with possible duplicates and I want to get a sorted sequence of all those objects without duplicates.

Right now I'm using a set to quickly gather all the elements discarding duplicates, convert it to a list and then sort that:

result = set()
for s in sequences:
    result = result.union(s)
result = list(result)
result.sort()
return result

It works but I wouldn't call it "pretty". Is there a better way?

like image 781
Luke404 Avatar asked Dec 07 '22 19:12

Luke404


1 Answers

This should work:

sorted(set(itertools.chain.from_iterable(sequences)))
like image 121
JBernardo Avatar answered Feb 15 '23 23:02

JBernardo