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?
Asked
Active
Viewed 71 times
0

ThePyGuy
- 17,779
- 5
- 18
- 45
-
Can you please share your code without inserting any image in Question – mhhabib May 17 '21 at 05:34
-
Please post your code directly in your question here. – Code-Apprentice May 17 '21 at 05:35
-
1The definition of a `set`: A set is an **unordered collection** with no duplicate elements. – Selcuk May 17 '21 at 05:35
-
3`set` objects have no order. If you require any particular order, then you cannot use a `set`. What you are asking for doesn't make sense. – juanpa.arrivillaga May 17 '21 at 05:35
1 Answers
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