Sorting lists

Lists can be sorted using the built-in Python sort method:

>>> x = [3, 8, 4, 0, 2, 1] >>> x.sort() >>> x

This does an in-place sort—that is, it changes the list being sorted. To sort a list without changing the original list, make a copy of it first.

>>> x = [2, 4, 1, 3] >>> y = x[:]

Sorting works with strings, too:

>>> x = ["Life", "Is", "Enchanting"] >>> x.sort() >>> x

The sort method can sortjust about anything, because Python can compare just about anything. But there is one caveat in sorting. The default key method used by sort requires that all items in the list be of comparable types. That means that using the sort method on a list containing both numbers and strings will raise an exception:

>>> x = [1, 2, 'hello', 3] >>> x.sort()

Traceback (most recent call last):

File "<stdin>", line 1, in <module> TypeError: unorderable types: str() < int()

On the other hand, we can sort a list of lists:

>>> x = [[3, 5], [2, 9], [2, 3], [4, 1], [3, 2]] >>> x.sorti) >>> x

According to the built-in Python rules for comparing complex objects, the sublists are sorted first by ascending first element and then by ascending second element.

sort is even more flexible than this—it's possible to use your own key function to determine how elements of a list are sorted.

Was this article helpful?

0 0

Post a comment