Python List sort() method
The list.sort
() method in Python sorts the items of the list in place.
Syntax
list.sort(key=None, reverse=False)
Parameter
reverse: If a Boolean value ‘True’ is passed, the sorting will be done in the descending order else for ‘False’ Boolean value sorting is done in ascending order.
key: This parameter represents a function to specify the sorting criteria(s)
Example 1
# Python program explaining
# the list.sort() method
# passing the alphabets list
alphaList = ['b', 'a', 'e', 'd', 'c']
print("Actual list: ",alphaList)
# sort the alphabets list in the ascending order
alphaList.sort()
# priningt the list in a sorted order
print('Sorted list:',alphaList)
Output
List: ['b', 'a', 'e', 'd', 'c'] Sorted list: ['a', 'b', 'c', 'd', 'e']
Example 2
# Python program explaining
# the list.sort() method
weekList = ['Sun', 'Thurs', 'Mon', 'Fri', 'Tues', 'Wed']
print("Actual week list: ",weekList)
# Sorting the week list in the descending order
weekList.sort(reverse=True)
# printing the sorted week list
print("Sorted week list:",weekList)
Output
Actual week list: ['Sun', 'Thurs', 'Mon', 'Fri', 'Tues', 'Wed'] Sorted week list: ['Wed', 'Tues', 'Thurs', 'Sun', 'Mon', 'Fri']
Example 3
# Python program explaining
# the list.sort() method
# returning the second element of the parameter
def sortArray(arr):
return arr[1]
# demonstrating the use of sorting by using using the second key
valList = [(11, 12), (13, 13), (11, 11)]
# sorting the array in ascending
valList.sort(key = sortArray, reverse = False)
# printing the sorted array
print("Sorted array in ascending order: \n",valList)
# sorting the array in descending
valList.sort(key = sortArray, reverse = True)
# printing the sorted array
print("Sorted array in descending order: \n",valList)
Output
Sorted array in ascending order: [(11, 11), (11, 12), (13, 13)] Sorted array in descending order: [(13, 13), (11, 12), (11, 11)]
