All Methods to Sort the list using sort() in Python

In this python tutorial, we are going to discuss various sorting methods in python.

The sort function in python can be used to sort a list in ascending, descending as well as in user-defined order.

Syntax:- name.sort() in Python

This will sort the list in ascending order.

Sorting a list in ascending order

Here we will see how to sort a list in ascending order in Python



Python code to sort the list in ascending order using sort()

numbers = [ 4 , 5 , 2 , 1]

   numbers.sort()

print( numbers )

This will result in the output list = [ 1, 2, 4, 5 ] in ascending order.

To sort the list in descending order we use,

Syntax:- name.sort( reverse=True )

Learn,

Sorting a list in descending order

Now, we are going to learn how to sort a list in descending order in Python

Python Code to sort the list in descending order using sort()

numbers = [ 1 , 9 , 5 , 2]

  numbers.sort( reverse = True )

 print ( numbers )

This will result in the list = [ 9, 5 , 2, 1 ] in descending order.

There are cases when we have a pair of values in the list and we have to sort the list according to our choice may be with respect to the first element in the list or with respect to the second element in the list.

Sorting a list on basis of user-defined choice

Here we can choose our own style of sorting a list in Python

Python code to sort the list on basis of user-defined choice

def sortSecond ( val )
      return val [1]

arr = [ (4,5) , (5,9) , (7,8) ]

  arr.sort ( key = sortSecond )

     print ( arr )

This will give the resultant arr = [ (4,5), (7,8), (5,9) ], sort the arr on basis of second value. If the requirement is to sort the list on basis of first value then we can use arr.sort (key = sort first).

learn,

Sorting a list of Strings in alphabetical order

Syntax :- name.sort()

Python Code to sort a list of strings in alphabetical order

str = [ ' Saurabh ' , ' Divyesh ' , ' Rishabh ' , ' Bahubali ' ]

   str.sort()

 print(str)

This will result the str = [‘Bahubali ‘, ‘Divyesh’, ‘Rishabh’, ‘Saurabh’]. As in alphabetical order ‘B’ comes first, then ‘D’, then ‘R’, then ‘S’.

Sorting a list of Strings on basis of its lengths

  Syntax :- name.sort(key=len)

Python Code to sort a list of strings on basis of its length

str = [ 'Sneha' , 'Shreya' , 'Shikha' , 'Radhikha' , 'Supriya' ]

   str.sort(key=len)

  print(str)

This will result the str =[‘Sneha’, ‘Shreya’, ‘Shikha’, ‘Supriya’, ‘Radhika’]. The given list str is sorted on basis of ascending order of length of the elements in a list. If two elements have the same length then their position in output is on basis of original position in a list.

Learn,

Duplicate Elements Removal of an Array or List using Python

One response to “All Methods to Sort the list using sort() in Python”

  1. Radhika Singh says:

    Nice post sir

Leave a Reply

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