Python sort() function is used to sorts the elements of a given list. It sorts the list ascending, descending, or user-defined order where ascending order is by default.
Note:
- Ascending order is by default in sort() method.
- It changes the original list and doesn’t return any value.
Syntax
1 |
list.sort(reverse=True|False, key=myFunc) |
Parameter Values
Both parameter are Optional.
- reverse:- if reverse = True will sort the list descending else as Default is (reverse=False)
- key:- A function to specify the sorting criteria(s)
Python sort list using sort function example
1. Sort the list “Ascending” order:
Numbers
1 2 3 4 5 6 |
numbers = [5, 3, 4, 2, 1] # Sorting list of Integers in ascending numbers.sort() print(numbers) |
Output: [1, 2, 3, 4, 5]
Strings
Example of how to python sort list of strings.
1 2 3 4 5 6 7 8 |
# vowels list vowels = ['e', 'a', 'u', 'o', 'i'] # sort the vowels vowels.sort() # print vowels print('Sorted list:', vowels) |
Output:
1 |
<samp>Sorted list: ['a', 'e', 'i', 'o', 'u']</samp> |
2. Sort the list “descending” order
Use and Set the parameter reverse=True
sorts the list in the descending order.
1 2 3 4 5 6 |
numbers = [5, 3, 4, 2, 1] # Sorting list descending numbers.sort(reverse=True) print(numbers) |
Output: [5, 4, 3, 2, 1]
Q: How to sort the list of lists in python?
Answer: If you want to sort on more entries, just make the key
function return a tuple containing the values you wish to sort on in order of importance. For example:
1 |
c2.sort(key = lambda row: (row[2],row[1],row[0])) |
Complete example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
c2 = [] row1 = [1, 22, 53] row2 = [14, 25, 46] row3 = [7, 8, 9] c2.append(row2) c2.append(row1) c2.append(row3) # OR direct can use # c2 = [[14, 25, 46], [1, 22, 53], [7, 8, 9]] c2.sort(key=lambda row: (row[2], row[1], row[0])) print(c2) |
Output: [[7, 8, 9], [14, 25, 46], [1, 22, 53]]
Q: How to sort the list alphabetically in Python?
Answer: Use The sorted()
function returns a sorted list where Strings are sorted alphabetically.
1 2 3 |
a = ("b", "g", "a", "d", "f", "c", "h", "e") print(sorted(a)) |
Output: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’]
Do comment if you have any doubts, something missing (you think must cover here), and suggestions on this tutorial.
Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.