a = set([2,1,5,3,2])
b = sorted(a)
print(b) # Returns a sorted List
In Julia, Is it possible to sort a Set?
Edit: There is no particular reason why I require a Set. I was reading the documentation and attempted to sort a simple Set, and was puzzled by the error returned.
sorted(a) isnât actually sorting the set itself in python eitherâitâs creating a new list from the elements of the set and sorting it. It should be quite similar to doing sort(collect(a)) in Julia. You could even define a helper function in your own code:
This assumes there will be a collection of values that needs to be sorted all the time and you also need to insert values between tests. The even larger question is which is the use case?
If only membership is needed, the Set would be the right structure.
If membership and ordering are important, but there are not many inserts, or the collection size is small, then a sorted Vector is probably the best.
If membership, ordering, and repeated/interleaved insertion is needed, then SortedSet is probably the best.
There is also the question if arbitrary removal is needed, if it is then Set/SortedSet are prefered over a sorted Vector.
Without knowing the exact use case it is impossible to prescribe a good solution, but Set then sort(collect(...)) does not seem a good choice in many cases, it shines only if: there can be no repetition of elements; there will be a lot of insertions/removals/âmembership testsâ; and after all of these, the remaining values need to be returned as a sorted sequence.