Sorting arrays in Python
Python comes with a number of built-in functions designed specifically for sorting array elements in different ways like alphabetically or numerically in ascending or descending order. Here we'll explore some of these functions most commonly used for sorting arrays. For a description of what an array is, click here.
Sort indexed arrays
The list.sort() function is used for sorting the elements of the indexed array in ascending order, alphabetically for letters and numerically for numbers. This is similar to the sort() in PHP. We can add the parameter, reverse=TRUE to the list.sort()function to sort the elements of the indexed array in descending order, again, alphabetically for letters and numerically for numbers. To do this in PHP, we would use the rsort() function. parameter.
numbers = [5, 2, 3, 1, 4] numbers.sort() numbers.sort(reverse=TRUE)
Line 2 will sort in ascending order and Line 3 will sort in descending order
Sort associative arrays by value
The sorted(ARRAY.values) function sorts the elements of an associative array in ascending order according to the value. It works just like sort(), but it preserves the association between keys and its values while sorting. This is similar to PHP's asort() method. We can add the the parameter, reverse=TRUE to the sorted( ARRAY.values) function to sort the associative array in descending order by value. In PHP, we would use the arsort() method.
numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4} sorted(numbers.values()) sorted( numbers.values(), reverse = TRUE )
Line 3 will output [1,2,3,4]. Line 4 will output [4,3,2,1]
Sorting associative array by key
The sorted(VALUE) function sorts the elements of an associative array in ascending order by their keys. It preserves the association between keys and its values while sorting. In PHP, we would use the ksort() method. We can add the the parameter, reverse=TRUE to the sorted( ARRAY) function to sort the associative array in descending order by key. In PHP, we would use the krsort() method.
numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4} sorted(numbers) sorted( numbers, reverse = TRUE )
Line 3 will output ['Fourth', 'first', 'second', 'third'].
Line 4 will output ['third', 'second', 'Fourth', 'first']