AppDividend
Latest Code Tutorials

Python Sort Set: How to Sort Set Values in Python

0

Python Set is an unordered collection with no duplicate elements. You can not sort the set because the whole meaning of the set itself does not allow that. Set objects support mathematical operations like union, intersection, difference, and symmetric difference.

Python Sort Set

To sort the values of the set in Python, use the sorted() method. The sorted() is a built-in method that returns the new sorted list from the items in iterable. The sorted() method takes two optional arguments, which must be defined as keyword arguments.

The sorted() method is giving you a list, not a set. That’s because the whole point of a set, both in mathematics, is that it’s not ordered: The sets {19, 21} and {21, 19} are the same set.

To create a set in Python, use the curly brackets and add elements between those brackets.

data = {11, 21, 46, 18, 19}

print(data)

Output

{18, 19, 21, 11, 46}

You can see that, by default, set values are unordered.

To sort the set values, use the sorted() method, which returns the list with sorted values.

data = {11, 21, 46, 18, 19}
print(data)

sortedValues = sorted(data)
print(sortedValues)

Output

{18, 19, 21, 11, 46}
[11, 18, 19, 21, 46]

You can see that the values are sorted in the list.

Now, don’t try to convert this list into the set using a set() method; otherwise, you will get the set, but the elements will be unordered because there is no way you can order the set elements. Set in Python is created for unordered elements.

Sets don’t have an order, and if you want an ordered collection, a list could be a good way to go.

This example shows four important characteristics of the sorted() method:

  1. The sorted() is a built-in Python method.
  2. The sorted() method with no additional arguments or parameters is ordering the values in data in ascending order, meaning smallest to largest.
  3. The original data variable is unchanged because the sorted() function provides a sorted output and does not change the original value in place.
  4. When the sorted() method is called, it provides an ordered list as a return value.

That is it for sorting a Python Set tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.