sort() in Python
The sort function can be used to sort the list in both ascending and descending order.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
To sort the list in ascending order.
# This will sort the given list in ascending order.
# It returns a sorted list according to the passed parameter.
This function can be used to sort list of integers, floating point number, string and others.
[1, 2, 3, 4] [1.68, 2.0, 2.01, 3.28, 3.67] ['For', 'Geeks', 'Geeks']
To sort the list in descending order.
list_name.sort(reverse=True) This will sort the given list in descending order.
[4, 3, 2, 1] [3.67, 3.28, 2.01, 2.0, 1.68] ['Geeks', 'Geeks', 'For']
list_name.sort() – it sorts in ascending order
list_name.sort(reverse=True) – it sorts in descending order
list_name.sort(key=…, reverse=…) – it sorts according to user’s choice
By default, sort() doesn’t require any extra parameters. However, it has two optional parameters:
reverse – If true, the list is sorted in descending order
key – function that serves as a key for the sort comparison
[(1, 1), (1, 2), (3, 3)] [(3, 3), (1, 2), (1, 1)]
Please refer Python Sort articles for more Python Sorting articles.
Thanks to striver for inputs on this topic.