List sort() method Python

The sort() method of list in Python is used for sorting elements.The elements are sorted in ascending order.The smaller number are placed first and the larger values are placed later.

>>> ls=[ 23 , 445 , 0 , (2)]
>>> ls.sort()
>>> ls
[0, 2, 23, 445] #sorted in ascending order

Another code example using string elements is given below.

>>> ls=[ 'New' , 'new' , 'text' , 'txt']
>>> ls.sort()
>>> ls
['New', 'new', 'text', 'txt'] 

While sorting string the first character is compared first with other strings,the string having the first minimum integer value is placed at first.Note here by minimum integer value we mean the value taken from the ASCII chart,link to ASCII chart here.Look at the chart the integer value of ‘N’ is 78 while ‘n’ has 110,’t’ has 116,so ‘New’ is placed first followed by ‘new’.Between ‘text’ and ‘txt’ since the first character are both ‘t’ the second character will be compared i.e. ‘e’ and ‘x’,’e’ has 101 and ‘x’ has 120 integer so ‘text’ comes first.


Points to note

To use sort() method the list object must contain only homogenous elements.The object cannot consist of a mixture of int,string, list or tuple elements.The sort() method can be used on objects having only int,or only string,or only list or only tuple elements.

>>> ls=[67, 'New' ]
>>> ls.sort()
ls.sort()
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    ls.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
>>> ls=[ (45,) , [34]]
>>> ls.sort()
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    ls.sort()
TypeError: '<' not supported between instances of 'list' and 'tuple'

As you can see trying to sort objects containing heterogenous elements render an error.



Leave a Reply

Your email address will not be published. Required fields are marked *