DEV Community

Mr #1738
Mr #1738

Posted on

Sorting values in a List with the sort() Method in Python.

Definition : is the the systematic arrangement of values or data in a list in a particular Order or format.
In python number of values or lists of strings can be sorted with the sort() method.For example enter the following into interactive shell:

>>> numbers = [1,-2,3,10,80,-4,30,4,8]
>>> numbers.sort()
>>> numbers
>>> numbers = [1,-2,3,10,80,-4,30,4,8]
>>> numbers.sort()
>>> numbers
[-4, -2, 1, 3, 4, 8, 10, 30, 80]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
>>> 
Enter fullscreen mode Exit fullscreen mode

Inclusion
There are three things to note when using sort(),First the sort() method sorts the list in place,Second you cannot sort lists that have both number values and string values in them,since python doesn't know how to compare these values.
Third , sort() uses “ASCIIbetical order” rather than actual alphabetical order for sorting strings. This means uppercase letters come before lower-case letters. Therefore, the lowercase a is sorted so that it comes after the uppercase Z.

Top comments (0)