Python: Sort

By Xah Lee. Date: . Last updated: .

Sort List In-Place

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 List In-Place 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']
listVar.sort(key=f, reverse=boolean)

Specify ascending or descending.

# 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]]

Sort Function: Return a Copy

sorted(key=f, reverse=boolean)
  • Return a sorted copy of the list. Does not modify original list.
xx = [1, 9, 2, 3]
yy = sorted(xx)

print(yy)
# [1, 2, 3, 9]

# original unchanged
print(xx)
# [1, 9, 2, 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