sort() – sort list

A list is one of the most powerful data structures used in Python. We can sort a list in Python in ascending or descending order.

Sort in ascending order

Code Explanation

LineDescription
1Declaration and initialization of the list myList with the values 5, 4, 2, 3 and 1
2The sort() method sorts by default in ascending order
4 + 5With the for loop each list element is output
myList = [5, 4, 2, 3, 1]
myList.sort()

for i in myList:
    print(i, end=" ")
Output
1 2 3 4 5 

Sort in descending order

Code Explanation

LineDescription
1Declaration and initialization of the list myList with the values 5, 2, 4, 1, 7 ,6
2If the parameter in the sort() method is set to True, the sorting is done in descending order.
4 + 5With the for loop each list element is output
myList = [5, 2, 4, 1, 7, 6]

myList.sort(reverse = True)

for i in myList:
    print(i, end=" ")
Output
7 6 5 4 2 1