# Python 3: Sort List, Matrix, Object

By Xah Lee. Date: . Last updated: .

This page is a Python beginner tutorial on sort.

## Sort Method, Sort In-Place

You can use the “sort” method. The “sort” method modifies the list.

```# python 3

li = [1,9,2,3]

li.sort() # the variable is modified

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

## Sort Function: Return a Copy

You can use the “sorted” function. This does not modify the variable. For example:

```# python 3

li = [1,9,2,3]

li2 = sorted(li)

print(li)   # [1, 9, 2, 3]
print(li2)  # [1, 2, 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

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

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

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

### Sort and Reverse

Another optional parameter is “reverse”. You can use it like this

```# 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 Arbitrary Object

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) # returns ["web7-s.jpg", "my23i.jpg", "fris88large.jpg", "my283.jpg"]```

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

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