Python: Sort

By Xah Lee. Date: . Last updated: .

Sort Methods

sort and reverse
SyntaxMeaning
lst.reverse()reverses the items of lst in place.
lst.sort()sort the items of lst in place
lst.sort(f)using predicate function f to sort. f takes 2 args, and return {1, 0, -1}, but any int works. The sign indicates order.
lst.sort(key=f)sort using f to extract a “key”. f takes 1 arg. Result is compared using cmp().
lst.sort(key=f, reverse=true/false)

Sort Function: Return a Copy

sorted(list) → return a sorted copy of the list. Does not modify original list.

# python 3

li = [1,9,2,3]

li2 = sorted(li)

print(li)   # [1, 9, 2, 3]
print(li2)  # [1, 2, 3, 9]

Sort Method, Sort In-Place

list.sort() → Sort list in-place. Return None. (The original list is modified.)

# python 3

li = [1,9,3]

# sort in-place
li.sort()

# the variable is modified
print(li)
# [1, 3, 9]

Sort by Column/Key

You can sort by specifying a optional parameter “key”. This is most useful for sorting a matrix.

# python 3

# sort a matrix by 2nd column

li = [[2,6],[1,3],[5,4]]

li.sort(key=lambda x:x[1])

print(li)  # [[1, 3], [5, 4], [2, 6]]

Sort and Reverse

Another optional parameter is “reverse”.

# python 3

# sort a matrix, by 2nd column, reverse order

li = [[2,6],[1,3],[5,4]]

li.sort(key=lambda x:x[1], reverse=True)

print(li);
# prints [[2, 6], [5, 4], [1, 3]]

Sort by An Ordering Function

Here's a more complex example. Suppose you have a list of strings.

'my283.jpg' 'my23i.jpg' 'web7-s.jpg' 'fris88large.jpg' …

You want to sort them by the number embedded in them.

You need to define a ordering function, and pass it to sort. The function should takes two strings, and compare the integer inside the string. Here's the solution:

# python 3

# sort by custom order

import re

li = [
"my283.jpg",
"my23i.jpg",
"web7-s.jpg",
"fris88large.jpg",
]

# compare number inside string
def myKey (myString):
    return float(re.findall(r"\d+", myString)[0]) # return number part in string

li.sort(key = myKey)

print(li)
# ["web7-s.jpg", "my23i.jpg", "fris88large.jpg", "my283.jpg"]

Here, we defined a function “myKey” to tell sort about the key to use.

Math of Ordering

In general, the function f used to determine the order of any two element must satisfy some constraints:

If the comparison function does not behave as the above, then it is not consistent. It means that the result ordered list may actually be different depending the order of the original list or how the language happens to implement sort.

The significance of all this is that in real software you may want to sort a list of complex object by a specialized ordering. For example, you may want to sort a list of triangles in 3D space by their orientation. Or, sorting image selections in a photo-editing program. It is in advanced cases like these, understanding the basic math about ordering is important. Otherwise, you might have a inconsistent result yet unable to locate any flaws in your code.

The order-deciding function given by the user is called a “predicate” in computer science. (A predicate function is any function that returns either true or false) And, it is usually defined inline using a pure function construct called “lambda”.

~2006 Thanks to Lasse Vågsæther Karlsen for informing me the existence of the sorted() function in Python 2.4.

Python List, Tuple, Dictionary

  1. List Basics
  2. Loop Thru List
  3. Map f to List
  4. Copy Nested List
  5. List Comprehension
  6. List Methods
  7. Sort
  8. Dictionary
  9. Loop Thru Dict
  10. Dict Methods
  11. Tuple
  12. Sets, Union, Intersection

If you have a question, put $5 at patreon and message me.

Python

  1. Python 3 Basics
  2. Python 2 Basics
  3. Python 2 and 3 Difference
  4. Print Version
  5. Builtin Help
  6. Quote String
  7. String Methods
  8. Format String
  9. Operators
  10. Complex Numbers
  11. True, False
  12. if then else
  13. Loop
  14. List Basics
  15. Loop Thru List
  16. Map f to List
  17. Copy Nested List
  18. List Comprehension
  19. List Methods
  20. Sort
  21. Dictionary
  22. Loop Thru Dict
  23. Dict Methods
  24. Tuple
  25. Sets
  26. Function
  27. Closure
  28. 2 Closure
  29. Decorator
  30. Class
  31. Object, ID, Type
  32. List Modules
  33. Write a Module
  34. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. File Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency

Web

  1. Send Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Append String in Loop
  7. Timing f timeit
  8. Keyword Arg Default Value Unstable
  9. Check Page Load Size
  10. Thumbnail Generation