Sorting
In this section we will use the following list or unordered numbers:
numbers = [7, 8, 1, 6, 5, 4, 3, 2, 10, 9]
What if we want to sort the list in ascending order? There are two ways to sort a list: temporarily and permanently.
During temporary sorting, the original list is not modified and a sorted copy is returned. Temporary sorting is done using the sorted()
function.
sorted_numbes = sorted(numbers) # sorted copy
print(sorted_numbes) # print sorted numbers
print(numbers) # print original list
which gives us:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[7, 8, 1, 6, 5, 4, 3, 2, 10, 9]
Note, that the originl list, numbers
, is not modified.
When sorting permanently, the original list is modified. Permanent sorting is done using the sort()
method:
numbers.sort() # sort in place
print(numbers)
with the original list changed:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Note, that the in-place, permanent, sorting is more efficient than temporary sorting. On the other hand, temporary sorting is safer because it does not modify the original list.