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.
List sort()
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. Syntax
list.sort(reverse=TrueFalse, key=myFunc)
- 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
sList = ['orange','banana','grapes','apple']
sList.sort(reverse = True)
print(sList)
output
['orange', 'grapes', 'banana', 'apple']
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.
key=str.lower

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.
def keyArgs(args):
return args[1]
numList = [('Five', '5'), ('Two', '2'), ('Four', '4'), ('One', '1'), ('Three','3')]
numList.sort(key=keyArgs)
print(numList)
output
[('One', '1'), ('Two', '2'), ('Three', '3'), ('Four', '4'), ('Five', '5')]
Sort using key parameter (reverse)
def keyArgs(args):
return args[1]
numList = [('Five', '5'), ('Two', '2'), ('Four', '4'), ('One', '1'), ('Three','3')]
numList.sort(key=keyArgs,reverse = True)
print(numList)
output
[('Five', '5'), ('Four', '4'), ('Three', '3'), ('Two', '2'), ('One', '1')]
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.
def sortLen(item):
return len(item)
items = ['aaaaa', 'aa', 'aaaa', 'aaa', 'a']
items.sort(key=sortLen)
print(items)
output
['a', 'aa', 'aaa', 'aaaa', 'aaaaa']
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.Sorting a List of Tuples by the first item
tList = [(8,12), (5,14), (7,18), (6,13), (10,19), (9,17)]
tList.sort()
print(tList)
output
[(5, 14), (6, 13), (7, 18), (8, 12), (9, 17), (10, 19)]
Sorting a List of Tuples by the second item
def secondItem(args):
return args[1]
tList = [(8,12), (5,14), (7,18), (6,13), (10,19), (9,17)]
tList.sort(key=secondItem)
print(tList)
output
[(8, 12), (6, 13), (5, 14), (9, 17), (7, 18), (10, 19)]
Sorting a list of objects
class Cars:
def __init__(self, Name, Year):
self.Name = Name
self.Year = Year
car1 = Cars('Ford',1903)
car2 = Cars('Toyota',1937)
car3 = Cars('Benz',1926)
car4 = Cars('Porsche',1931)
carList = [car1, car2, car3, car4]
carList.sort(key=lambda x: x.Name)
print([item.Name for item in carList])
carList.sort(key=lambda x: x.Year)
print([item.Year for item in carList])
output
['Benz', 'Ford', 'Porsche', 'Toyota']
[1903, 1926, 1931, 1937]
Related Topics