Sorting in Python

How to use python sorted()

Sorting in Python

Most times when finding solutions to a problem first sorting the data can greatly simplify the process and also produce a faster and cleaner solution.

An example is finding the 1st and 2nd greatest number in a list. After sorting in descending order the answer is the 1st and 2nd element in the sorted list. Very elegant and straightforward!

Python sorted()

In this tutorial, we will introduce the python sorted() method then show you how to perform basic sorting with it.

Definition

The sorted() function sorts the elements of a given iterable in a specific order (ascending or descending) and returns it as a list.

Syntax

The syntax of the sorted() function is: sorted(iterable, key=None, reverse=False)

Parameters

sorted() can take a maximum of three parameters:

iterable - A sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator.

reverse (Optional) - If True, the sorted list is reversed (or sorted in descending order). Defaults to False if not provided.

key (Optional) - A function that serves as a key for the sort comparison. Defaults to None.

Example (list and tuple)

# list
mylist = [2, 6, 1, 10, 40, 7]
# tuple
mytuple = (3, 5, 2, 1, 15, 7)

# sort and output a sorted list/tuple
print(sorted(mylist))
print(sorted(mytuple))

Output

[1, 2, 6, 7, 10, 40]
(1, 2, 3, 5, 7, 15)

Example (dictionary)

# dict
mydict = {"e": 5, "a": 1, "c": 3, "d": 4, "b": 2}

# sort and output a sorted list of dictionary keys
print(sorted(mydict))

Output

["a", "b", "c", "d", "e"]

See that when sorting a dictionary it is the keys that are sorted and not values. That is because the keys are the access points to the values.

Example (Sorting in Descending Order)

# list
mylist = [2, 6, 1, 10, 40, 7]
# tuple
mytuple = (3, 5, 2, 1, 15, 7)
# dict
mydict = {"e": 5, "a": 1, "c": 3, "d": 4, "b": 2}

# sort and output a sorted list/tuple
print(sorted(mylist, reverse=True))
print(sorted(mytuple, reverse=True))
print(sorted(mydict, reverse=True))

Output

[40, 10, 7, 6, 2, 1]
(15, 7, 5, 3, 2, 1)
["e", "d", "c", "b", "a"]

See that when reverse=True the elements are sorted in descending order (from highest to lowest).

Custom sort with the key parameter

Sometimes for certain reasons, you may want to provide your criteria for sorting; the key parameter is what you need. It is set to a function whose return value is used for sorting.

Example (Custom sort)

Let's sort dictionaries by value instead of keys.

mydict = {"a": 10, "b": 5, "c": 7}

# sort by value [10, 5, 7] and output result
print(sorted(mydict, key=lambda x: mydict[x]))

Output

["b", "c", "a"]

We used lambda because it was simple logic. For more complex logic you will need to define a function using def keyword. Just like the lambda, the function will accept a value (which is an item in the iterable) and whatever it returns will be used for the sorting.

Real-World Examples

Let us look at some real-world use cases for sorting.

Finding the best, median, and worst student (simple)

Given a list of students scores find the best, median, and worst scores.

# students scores
scores = [70, 50, 20, 40, 80, 35, 15, 85]

# sort scores in descending order
scores = sorted(scores, reverse=True)
# output 1st element as Best Score
print('Best Score: {}'.format(scores[0]))
# output middle element as the median score
print("Median Score: {}".format(scores[len(scores)//2]))
# output last element as worst score
print("Worst Score: {}".format(scores[-1]))

Output

Best Score: 85
Median Score: 40
Worst Score: 15

Finding the best, median, and worst student (Complex)

Given a list of tuples of students (name, scores) find the best, median, and worst student.

#students scores
scores = [
    ('James', 70, 50, 20), 
    ('Amaka', 40, 80, 35), 
    ('John', 15, 85, 45), 
    ('Joel', 35, 25, 70), 
    ('Miracle', 70, 85, 75)
]

#define custom sort function to use as a key.
def sorter(student):
    # sum and return student scores
    return sum(student[1:])

#sort scores using defined function as key and in descending order
scores = sorted(scores, key=sorter, reverse=True)

#output 1st element as the best student
print('Best Student: {}'.format(scores[0]))
#output middle element as median student
print('Median Student: {}'.format(scores[len(scores)//2]))
#output last element as the worst student
print('Worst Student: {}'.format(scores[-1]))

Output

Best Student: ('Miracle', 70, 85, 75)
Median Student: ('John', 15, 85, 45)
Worst Student: ('Joel', 35, 25, 70)

Conclusion

Sorting is a very powerful tool that every developer should have. It is the foundation of many awesome algorithms like the Binary Search and many Search Algorithms. Most times just sorting your data can make a problem that seemed very complex to be very easy to solve.

Thank you for reading to the end. Please like, share, and comment.