Python List sort()

Previous
Next

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

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:

‚ÄčlistOfNames before sorting: [‘Sam’, ‘Mary’, ‘Martin’, ‘John’]
listOfNames after sorting in ascending order: [‘John’, ‘Martin’, ‘Mary’, ‘Sam’]
listOfNames after sorting in descending order: [‘Sam’, ‘Mary’, ‘Martin’, ‘John’]

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:

listOfNames before sorting: [‘Sam’, ‘Mary’, ‘Martin’, ‘John’]
listOfNames after sorting on the basis of len: [‘Sam’, ‘Mary’, ‘John’, ‘Martin’]

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:

listOfNames before sorting: [1, ‘two’, 3, ‘four’]
—————————————————————————
TypeError Traceback (most recent call last)
in ()
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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog