Python: Sort

By Xah Lee. Date: . Last updated: .

Two ways to sort, the method sort and the function sorted

There are two ways to sort:

Difference between sort vs sorted

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