Sort the List in python: sort() Function in python sorts the element of given list in either ascending order or descending order. sort the list by its length. sort the list by list.sort() function and sorted() function.
Syntax of sort() function:
- list.sort(key=…, reverse=…)
2. sorted(list, key=…, reverse=…)
Sort the list in python : Ascending order:
Method 1:
List1=[5,6,3,1,2,7,4] List2=['alex','zampa','micheal','jack','milton'] # sort List1 and List2 in Ascending order sorted(List1) sorted(List2)
In the above code we sorted list1 and list2 in ascending order with the help of sorted() function, so the output will be
[1, 2, 3, 4, 5, 6, 7] ['alex', 'jack', 'micheal', 'milton', 'zampa']
Method 2:
Sort list in ascending order with List.sort() Function
List1=[5,6,3,1,2,7,4] List2=['alex','zampa','micheal','jack','milton'] # sort List1 in Ascending order List1.sort() print List1 # sort List2 in Ascending order List2.sort() print List2
NOTE: List.sort() Function sorts the original list
so the output will be
[1, 2, 3, 4, 5, 6, 7]
[‘alex’, ‘jack’, ‘micheal’, ‘milton’, ‘zampa’]
Sort the list in python: Descending order:
Method 1:
Now let’s sort list1 and list2 in descending order with the help of sorted() function, so the output will be
List1=[5,6,3,1,2,7,4] List2=['alex','zampa','micheal','jack','milton'] # sort List1 and List2 in Descending order sorted(List1,reverse=True) sorted(List2,reverse=True)
reverse= True argument in sorted function sorts the list in descending order
so the output will be
[7, 6, 5, 4, 3, 2, 1]
[‘zampa’, ‘milton’, ‘micheal’, ‘jack’, ‘alex’]
Method 2:
Sort list in Descending order with List.sort() Function
List1=[5,6,3,1,2,7,4] List2=['alex','zampa','micheal','jack','milton'] # sort List1 in descending order List1.sort(reverse=True) print List1 # sort List2 in descending order List2.sort(reverse=True) print List2
NOTE: List.sort() Function sorts the original list
so the output will be
[7, 6, 5, 4, 3, 2, 1]
[‘zampa’, ‘milton’, ‘micheal’, ‘jack’, ‘alex’]
Sort the list based on length:
Lets sort list by length of the elements in the list
List2=['alex','zampa','micheal','jack','milton'] # sort the List2 by descending order of its length List2.sort(reverse=True,key=len) print List2
in the above example we sort the list by descending order of its length, so the output will be