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

4
  • Can you please share your code without inserting any image in Question Commented May 17, 2021 at 5:34
  • Please post your code directly in your question here. Commented May 17, 2021 at 5:35
  • 1
    The definition of a set: A set is an unordered collection with no duplicate elements. Commented May 17, 2021 at 5: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. Commented May 17, 2021 at 5:35

1 Answer 1

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}
Sign up to request clarification or add additional context in comments.

3 Comments

Thankyou for answer. I tried it. But my question is Why the set(sorted()) doesn't sort the list?
sorted does sort the list! Then you put the result of the sorting in a set and now it's unordered again.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.