Sort Function in Python Code

In Python, You can sort a list or array of numbers & strings using the built in function.

The code below creates a numeric & string array. Then sorts is ascending & descending. The default is ascending.

Lets see how do this with a Python code example:

#Sort Function in Python
#Define List
intList = [2,4,3,5,1]
strList=["sort","this","list"]

#Sort list
intList.sort()
strList.sort()

#Print list
print("Ascending: ", intList)
print("Ascending: ",strList)

#Sort Descending - Reverse
intList.sort(reverse=True)
strList.sort(reverse=True)
print("Descending: " , intList)
print("Descending: ", strList)

There are lot more options available in sort function in Python. We will be publishing lot more code samples in the upcoming articles.

External Reference: Click here to read more about the Python Sort function for lists.