The sort function can be used to sort the list in both ascending and descending order.
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.
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.
- Comparison among Bubble Sort, Selection Sort and Insertion Sort
- Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
- Odd-Even Sort / Brick Sort
- Bucket Sort To Sort an Array with Negative Numbers
- Serial Sort v/s Parallel Sort in Java
- Program to sort an array of strings using Selection Sort
- C/C++ Program for Odd-Even Sort / Brick Sort
- Java Program for Odd-Even Sort / Brick Sort
- Insertion sort to sort even and odd positioned elements in different orders
- Quick Sort vs Merge Sort
- Odd Even Transposition Sort / Brick Sort using pthreads
- Sort an Array which contain 1 to N values in O(N) using Cycle Sort
- Add elements in start to sort the array | Variation of Stalin Sort
- Merge Sort vs. Insertion Sort
- sort() vs. partial_sort() vs. nth_element() + sort() in C++ STL
- Sort all even numbers in ascending order and then sort all odd numbers in descending order
- Python | Sort Python Dictionaries by Key or Value
- List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
- Ways to sort list of dictionaries by values in Python - Using lambda function
- Ways to sort list of dictionaries by values in Python – Using itemgetter
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.