In the above program, we can see we have declared a list of fruits which are having different lengths of words in the list. Print("The list of fruits will be sorted according to the length of the letters in descending order:") Print("The list of fruits are as follows:",fruits) To sort in ascending order, we have to specify the reverse parameter as false or just specify it as sort() method. In the below example, we will see how to sort the length of the values of the list in descending order. Now let us see how to sort the list according to the length of the letters of words, and we can sort in either of the ways, such as ascending or descending order. This list is sorted in descending order using a parameter “reverse”, which is set to “True” so that the list can be sorted in reverse order or descending order. In the above program, we have declared the sort() method for the given list, and it is named as “num”. Print("The above list is sorted in descending order is as follows:",num) Print("The given list for sorting is as follows:", num) Now let us see another example in which we can sort in descending order. As we can see, the above program has only the sort() method, So by default, the list is sorted in ascending order. In the above program, we can see that we have sorted the simple list. Print("The above list is sorted as follows:",num) Print("The given list to sort is as follows:", num) Examples of Python Sort Listįollowing are the examples of python sort list Example #1 The second syntax can also be used, which works similar to the first one, and if we want the list to be sorted in descending order, then we have to set the reverse parameter as “True” else set it “false”, and the key parameter is used for a function that can specify sorting criteria(s). In the above syntax, we can see the first one is very simple, and if it just specified as sort(), then it will by default sort the elements in ascending order and the “func” parameter, which is used to specify any of the sorting criteria’s. Or List.sort (reverse = True or False, key = func_name)
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |