
In the above article, we have shown how to sort python list in ascending, descending and user-defined orders. Similarly, you can sort a list of tuples in descending order just by adding (reverse=True) > tuple_list.sort(key = get_second,reverse=True) We define a function get_second to get the second element of each tuple. Here is an example where sort a tuple based on its second element. Here is the syntax to sort lists in a user-defined order. It is useful if your list consists of tuples or dictionary data types. You can also sort python lists in user defined order. Similarly, you can sort list of strings in descending order. Please note, you need to enter True with a capital T, else you will get an error. You can sort python list in descending order by adding reverse=True option. > str_list=Īlso read : How to Configure UFW Firewall in Linux In case of strings, it will sort your list alphabetically. Sort() function sorts both numbers and strings in ascending order.

You can sort a python list in ascending order by simply calling the sort function on your list. list_name.sort()Īlso read : How to Install Google SDK in Ubuntu We will use the sort function to sort python lists in ascending, descending and user-defined order.

Python lists come with pre-built sort function that allows you to easily sort data in numerous ways. In this article, we will look at how to sort list in Python. For example, you may need to sort a list of integers, floating point numbers, strings or other data types. Sometimes you may need to sort list in python to sort in different ways.
