How to Python list sort()
Python list is a collection which is ordered and changeable. It can holds a number of other objects, in a given order. List is a compound data type which means you can have different data types under a list, for ex. you can have integer, float and string items in a same list. Also, the list type implements the sequence protocol , so it allows you to add and remove objects from the sequence.
The sort() method performs the sorting of list elements in ascending , descending or user defined order . When we call sort() method, it traverses the list elements in a loop and rearranges them in ascending order when there are no arguments. When we pass reverse = true , then the list gets sorted in the descending order.
- reverse - Default is reverse=False, while reverse=True will sort the list descending.(Optional)
- key - A method to specify the sorting criteria (Optional)
Sort list of numbers
Sort list of strings
Sort list of strings in descending order
If any of the list element is Uppercase , let's see what happens.
It is because Python treats all Uppercase letters to be lower than Lowercase letters, if you want you can change it.
Sort using key parameter
The key parameter in sort() method specifies a function that will be called on each list item before making comparisons. If you want your own implementation for sorting , you can use key parameter as an optional parameter.
Sort using key parameter (reverse)
Sort the list by the length of the values
A new function "sortLen" that returns the length of the list elements and add this function as key of sort() function.
Sorting a List of Tuples
A Tuple is a collection of Python objects that written with round brackets and separated by commas. The difference between Tuple and List is that we cannot change the elements of a tuple once it is assigned whereas, in a list, elements can be changed.