Python: Sort
Two ways to sort, the method sort and the function sorted
There are two ways to sort:
- The
sort
method. - The
sorted
function
Difference between sort vs sorted
- The
sort
method can only sort list, not iterable. - The
sort
method change the list variable in-place.
- The
sorted
function can sort any iterable. - The
sorted
function returns a copy.
Sort Function
sorted(iterable, key=f, reverse=boolean)
-
Return a sorted copy of the list. Original is not changed.
xx = [1, 9, 2, 3] yy = sorted(xx) print(yy) # [1, 2, 3, 9] # original unchanged print(xx) # [1, 9, 2, 3]
# sort a matrix by 2nd column xx = [[2, 6], [1, 3], [5, 4]] yy = sorted(xx, key=lambda x: x[1]) print(yy) # [[1, 3], [5, 4], [2, 6]]
Sort method
listVar.sort()
-
- Sort the items of listVar in-place.
- Return
None
.
xx = [1,9,3] # sort in-place xx.sort() print(xx) # [1, 3, 9]
Sort by Key
listVar.sort(key=f)
-
- Sort by using f to extract a key for comparison.
- f is feed a element in the list.
- Value of f is compared using
cmp()
.
💡 TIP: This is most useful for sorting a matrix.
# sort a matrix by 2nd column xx = [[2, 6], [1, 3], [5, 4]] xx.sort(key=lambda x: x[1]) print(xx) # [[1, 3], [5, 4], [2, 6]]
import re # sort by custom order # compare number inside string xx = [ "x283.jpg", "x23i.jpg", "aa7-s.jpg", "bb88mm.jpg", ] def getNumber(xstr): """return number part in string""" return float(re.findall(r"\d+", xstr)[0]) xx.sort(key=getNumber) print(xx) # ['aa7-s.jpg', 'x23i.jpg', 'bb88mm.jpg', 'x283.jpg']
Specify ascending or descending
listVar.sort(key=f, reverse=boolean)
-
# sort a matrix, by 2nd column, reverse order xx = [[2, 6], [1, 3], [5, 4]] xx.sort(key=lambda x: x[1], reverse=True) print(xx) # [[2, 6], [5, 4], [1, 3]]
Reverse List
listVar.reverse()
-
Reverses the items of listVar in-place.
~2006 Thanks to Lasse Vågsæther Karlsen for informing me the existence of the sorted()
function in Python 2.4.
Python, Data Structure
- Python: List
- Python: Generate List: range
- Python: List Comprehension
- Python: List Methods
- Python: Iterate List
- Python: Map f to List
- Python: Filter List
- Python: Iterator to List
- Python: Copy Nested List, Shallow Copy vs Deep Copy
- Python: Interweave Lists to Tuples, Transpose
- Python: Sort
- Python: Convert List to Dictionary
- Python: Dictionary
- Python: Iterate Dictionary
- Python: Dictionary Methods
- Python: Tuple
- Python: Sets, Union, Intersection
- Python: Sequence Types
- Python: Read Write JSON