How to sort a Python List
Sort a Python List
The sort
method sorts a list in place.
It changes the original list.
sort method has the following syntax.
alist.sort(key=None, reverse=False)
Sorts alist in-place, in ascending order by default. If
passed, key
specifies a function of one argument that is
used to extract or compute a comparison value from each
list element. If reverse
is passed and true, the list elements
are sorted as if each comparison were reversed.
For example:
alist.sort(key=str.lower, reverse=True)
x = [4, 6, 2, 1, 7, 9]
x.sort()
print x
The code above generates the following result.
The following code copies y to x, and then sort x.
y = [4, 6, 2, 1, 7, 9] # w ww . ja v a 2 s . c om
x = y[:]
x.sort()
print x
print y
y[:] is a slice containing all the elements of y, effectively a copy of the entire list. Simply assigning y to x wouldn't work because both x and y would refer to the same list.