Python list sort function with examples
Python list sort function:
Python list has a inbuit sort function to sort the values in list. This function automatically sort the list values. By using this function we can sort numeric values and strings.
Syntax : list_name.sort(key=’’, reverse=’’)
#numeric list numbers = ['55', '66', '88', '44', '33'] # sort the numeric numbers.sort() # print Numbers print('Sorted Numeric list:', numbers)
Output:
Sorted Numeric list: ['33', '44', '55', '66', '88']
# characters list characters = ['d', 'g', 'z', 'o', 'a'] # sort the characters characters.sort() # print characters print('Sorted Character list:', characters)
Output:
Sorted Character list: ['a', 'd', 'g', 'o', 'z']
Reverse: ( Descending Order)
By default this function sort in ascending order of the list. If you want descending order, you need to use reverse=True as a argument in sort function.
#numeric list numbers = ['55', '66', '88', '44', '33'] # sort the numeric numbers.sort(reverse=True) # print Numbers in reverse print('Sorted Reverselist:', numbers)
Output:
Sorted Reverselist: ['88', '66', '55', '44', '33']
# characters list characters = ['d', 'g', 'z', 'o', 'a'] # sort the characters characters.sort(reverse=True) # print characters print('Sorted Character in Reverse list:', characters)
Output:
Sorted Character in Reverse list: ['z', 'o', 'g', 'd', 'a']