0

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?

my tried code

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45

1 Answers1

1

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}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Thankyou for answer. I tried it. But my question is Why the set(sorted()) doesn't sort the list? – Jidnyasa Sonavane May 17 '21 at 05:54
  • `sorted` does sort the list! Then you put the result of the sorting in a set and now it's unordered again. – Matthias May 17 '21 at 07:56
  • @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. – paxdiablo May 17 '21 at 07:57