In this tutorial, we will see about Python List‘s sort method.Python List sort method is used to sort the list either in ascending or descending order.
Python List sort syntax
1 2 3 |
list1.sort([key=..,reverse=..]) |
here list1 is object of list.As you can see key and reverse are optional parameters.
Python List sort example
You can simply call remove method to delete an element from the list.
Let’s understand this with the help of simple example.
listOfNames=[‘Sam’,’Mary’,’Martin’,’John’]
print("listOfNames before sorting:",listOfNames)
listOfNames.sort()
print("listOfNames after sorting in ascending order:",listOfNames)
listOfNames.sort(reverse=True)
print("listOfNames after sorting in descending order:",listOfNames)
Output:
As you can see here, we have sorted in ascending and descending order.
You can also sort list on the basis of key function. Let’s understand with the help of example.
listOfNames=[‘Sam’,’Mary’,’Martin’,’John’]
print("listOfNames before sorting:",listOfNames)
listOfNames.sort(key=len)
print("listOfNames after sorting on the basis of len:",listOfNames)
Output:
What if list has mixed data type
If you have different data type in the list and they are not comparable then sort method will raise TypeError.
listOfNames=[1,’two’,3,’four’]
print("listOfNames before sorting:",listOfNames)
listOfNames.sort()
print("listOfNames after sorting:",listOfNames)
Output:
TypeError Traceback (most recent call last)
1 listOfNames=[1,’two’,3,’four’] 2 print(“listOfNames before sorting:”,listOfNames)
—-> 3 listOfNames.sort()
4 print(“listOfNames after sorting:”,listOfNames)
5
TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’
That’s all about Python List sort method.