Saturday, May 16, 2009

How to sort a Python list

Suppose that you have a Python list,

[1, 4, 3, 7, 2, 12, -3, 3]

that needed to be sorted.

The list can be sorted by directly applying the sort() method to the list, and indirectly by using the sorted().

Using sort()


The list will be sorted and the list will now become the new sorted list.
>>> y = [1, 4, 3, 7, 2, 12, -3, 3]
>>> y.sort()
>>> y
[-3, 1, 2, 3, 3, 4, 7, 12]

Using sorted()


The list will be sorted as a new list.

We can create a new sorted list, and the original remains.
>>> y = [1, 4, 3, 7, 2, 12, -3, 3]
>>> sorted(y)
[-3, 1, 2, 3, 3, 4, 7, 12]
>>> y
[1, 4, 3, 7, 2, 12, -3, 3]