When I used sorted on the set in python it returns sorted list. But I want to return the set. I tried set(sorted()) but it doesn't sort the set.
I tried another way. But why set(sorted()) isn't sorting the set?
1 Answer
Sets are unsorted, that is their nature. Taking a set (or any collection) then sorting it, then making a set out of that, will be unlikely to produce sorted results.
If you require the items in a sorted manner, you should turn them into something that can be sorted (like a list, which is what you get from sorted(someSet)). For example:
>>> a = {100, 99, 1, 2, 5, 6} # A set
>>> sorted(a) # A sorted list from that set.
[1, 2, 5, 6, 99, 100]
>>> set(sorted(a)) # An (unsorted) set from that sorted list.
{1, 2, 99, 100, 5, 6}
3 Comments
Jidnyasa Sonavane
Thankyou for answer. I tried it. But my question is Why the set(sorted()) doesn't sort the list?
Matthias
sorted does sort the list! Then you put the result of the sorting in a set and now it's unordered again.paxdiablo
@Jidnyasa: because, as I explain in the first paragraph, turning a sorted collection back into a set makes it unsorted again. Sets are unordered, regardless of the order of the thing you make them from.
set: A set is an unordered collection with no duplicate elements.setobjects have no order. If you require any particular order, then you cannot use aset. What you are asking for doesn't make sense.