Sorting of Lists in Python

Python provides very detailed procedures for sorting of lists. In this study we look at different ways in which this method works.
Simple Sorting
Python provides the sorted method which sorts a list in ascending order. It returns a sorted list, but doesn’t change the input list.

l1=[8,2,4,3,5,6,7,1]
print(l1)
l2=sorted(l1)
print(l1)
print(l2)

Output
[8, 2, 4, 3, 5, 6, 7, 1]
[8, 2, 4, 3, 5, 6, 7, 1]
[1, 2, 3, 4, 5, 6, 7, 8]

The sort method
Is part of the List and will be called as l.sort(). This will sort the l list. No list is returned.

 

l1=[8,2,4,3,5,6,7,1]
print(l1)
l1.sort()
print(l1)
Output
[8, 2, 4, 3, 5, 6, 7, 1]
[1, 2, 3, 4, 5, 6, 7, 8]

You can sort lists of strings as well:
l1=[“Mango”,”Apple”,”Lemon”]
print(l1)
l1.sort()
print(l1)

[‘Mango’, ‘Apple’, ‘Lemon’]
[‘Apple’, ‘Lemon’, ‘Mango’]

What happens if we mix integers and strings?

l1=[“Mango”,1,”Lemon”]
print(l1)
l1.sort()
print(l1)
We get an error message.
TypeError: ‘<‘ not supported between instances of ‘int’ and ‘str’

Python used to support a cmp parameter for specifying the sorting order of the methods. This method has now being discontinued.

Sorting can be done in reverse order using the reverse named parameter.

l1=[2,1,3]
print(l1)
l1.sort(reverse=True)
print(l1)
l1.sort()
print(l1)
l1.sort(reverse=False)
print(l1)

Output
[2, 1, 3]
[3, 2, 1]
[1, 2, 3]
[1, 2, 3]

Sorted works the same way.

l1=[2,1,3]
print(l1)
sorted(l1,reverse=True)
print(l1)
l1=sorted(l1)
print(l1)
l1=sorted(l1,reverse=False)
print(l1)

[2, 1, 3]
[2, 1, 3]
[1, 2, 3]
[1, 2, 3]

The key is used to provide sorting functionality to a function of the list values.
For example we can sort the list by len() which is length of the string.

l1=[“Varanasi”,”Pune”,”Delhi”]
print(l1)
sorted(l1,reverse=True)
print(l1)
l1=sorted(l1)
print(l1)
l1=sorted(l1,reverse=False, key=len)
print(l1)

[‘Varanasi’, ‘Pune’, ‘Delhi’]
[‘Varanasi’, ‘Pune’, ‘Delhi’]
[‘Delhi’, ‘Pune’, ‘Varanasi’]
[‘Pune’, ‘Delhi’, ‘Varanasi’]

 

Leave a Reply