Python - Sort list

By xngo on June 19, 2019

In Python, you can sort a list in ascending, descending or user-defined order.

Sort list in ascending order

Sort list of numbers in ascending order.

my_list = [ 5, 6, 5, 1, 4];
my_list.sort()
print(my_list)

Output

[1, 4, 5, 5, 6]

Sort list in descending order

Sort list of numbers in descending order.

my_list = [ 5, 6, 5, 1, 4];
my_list.sort(reverse = True)
print(my_list)

Output

[6, 5, 5, 4, 1]

Sort list in user-defined order

To sort using your own order, you have to provide your sort function as key parameter to sort(). The examples below show how to sort by the second character of each string.

fruits = [ 'pineapple', 'apple', 'guava' ]
 
# User defined sort function:
#   Compare 2nd character of string. Note first character index starts from 0.
def sort_by_2nd_char(val):
    return val[1]
 
# Sort list in ascending using user defined function.
fruits.sort(key = sort_by_2nd_char)
print(fruits)
 
# Sort list in descending using user defined function.
fruits.sort(key = sort_by_2nd_char, reverse = True)
print(fruits)
 

Output

['pineapple', 'apple', 'guava'] # 2nd character: i, p, u
['guava', 'apple', 'pineapple'] # 2nd character: u, p, i

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.