The 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
list.sort(reverse=True|False, key=myFunc)
Parameter Values
Both parameters 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
numbers = [5, 3, 4, 2, 1]
# Sorting list of Integers in ascending
numbers.sort()
print(numbers)
Output:
Strings
Example of how to python sort a list of strings.
# vowels list vowels = ['e', 'a', 'u', 'o', 'i'] # sort the vowels vowels.sort() # print vowels print('Sorted list:', vowels)
Output:
Sorted list: ['a', 'e', 'i', 'o', 'u']
2. Sort the list “descending” order
Use and Set the parameter reverse=True
sorts the list in descending order.
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:
c2.sort(key = lambda row: (row[2],row[1],row[0]))
Complete example
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.
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.