Python List sort()

Python list‘s sort() function method is used to sort list.
You can sort either in ascending or descending order using this function.


key: It provides function that can be used as key. It is optional parameter.
reverse: It is also optional parameter and can be either True or False. If reverse=true then list will be sorted in reversed order.


It does not return any value.It updates the original list


Let’s see a very simple example:

#Sort list of integers l= [10,34,54,23,21,2,4,67,52] l.sort() print("Sorted list: ",l) #Sort list of String listOfFruits= ['orange','apple','banana','kiwi'] listOfFruits.sort() print("Sorted list of fruits: ",listOfFruits) #Sort list of String in reverse order listOfAnimals= ['Horse','Dog','Wolf','Cat','Bat'] listOfAnimals.sort(reverse=True) print("Sorted list of animals in reverse order: ",listOfAnimals)


Sorted list: [2, 4, 10, 21, 23, 34, 52, 54, 67]
Sorted list of fruits: [‘apple’, ‘banana’, ‘kiwi’, ‘orange’]
Sorted list of animals in reverse order: [‘Wolf’, ‘Horse’, ‘Dog’, ‘Cat’, ‘Bat’]

Sort using key function

We are going to sort list based on key function.

#Sort list of String listOfFruits= ['orange','apple','watermelon','kiwi'] listOfFruits.sort(key=len) print("Sorted list of fruit by String length",listOfFruits)


Sorted list of fruit by String length [‘kiwi’, ‘apple’, ‘orange’, ‘watermelon’]

That’s all about Python List’s sort() method.

Leave a Reply

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