Python Sort Function
Sorting values is a common practice in most programming languages. Because of this, and because of Python's focus on collections of data such as Lists, the Python libraries contain a sort method, called "sorted," that handles sorting operations. And while the List data type also has its own sort method, the external "sorted" method represents a more versatile option in many situations.
-
The List.sort() Method
-
For sorting lists in place, a programmer would typically use the "sort()" method internal to the List data type. The sort method takes the current list and sorts it to ascending order, as in this example:
>>>l = [5, 4, 7, 2, 1]
>>>l.sort()
>>>l
[1, 2, 4, 5, 7]
The list will now remain sorted wherever the programmer should decide to pass it or use it.
The "sorted()" Method
-
The "sorted()" method performs the same operation on its most basic use. Taking a list, the sorted method will sort the values in the list in ascending order:
>>>l2 - [6, 8, 4, 3, 2, 5]
>>>sorted(l2)
[2, 3, 4, 5, 6, 8]
Both the list.sort() and sorted() methods also accept a "reverse" argument, which will sort the values in descending order:
>>>l.sort(reverse=True)
>>>l
[7, 5, 4, 2, 1]
>>>sorted(l2, reverse=True)
>>>l2
[8, 6, 5, 4, 3, 2]
-
Sorting Lists by Values
-
Certain lists might contain values based on actual organizing data, rather than just a list of numbers or strings. A group of lists that contains an employee's name, age and ID might look similar to these examples:
>>>e1 = ['Bob', 29, 1]
>>>e2 = ['Jane', 27, 2]
>>>e3 = ['Jill', 31, 3]
A programmer sorting these lists might want to sort by the second value representing age. The programmer can give an extra "key" parameter exclusive to the sorted class which allows the programmer to sort based on specific values, as in this example:
>>>import operator
>>>employees = [e1, e2, e3] //a list of employee lists
>>>sorted(employees, key=operator.itemgetter(1))
[['Jane', 27, 2], ['Bob', 29, 1], ['Jill', 31, 3]]
Methods and Searching
-
The sorted class also allows a programmer to sort lists based on the return values of method calls, using the "methodcaller" key as an argument. For example, the programmer might want to sort values based on the number of occurrences of the letter "x" in each entry, as in this example:
>>>import operator
>>>l4 = ['rrrxxxyxx', 'xxxtx', 'x']
>>>sorted(l4, key=operator.methodcaller('count', 'x'))
['x', 'xxxtx', 'rrrxxxyxx']
-
References
- Photo Credit Ablestock.com/AbleStock.com/Getty Images