Container Data Structures

Sorting Lists

The order of items in a list are preserved until the list is modified by inserting an item to or removing an item from the list. However, preserving the order does not guarantee the items to be sorted.

The sort() method reorders the items in a list based on an increasing/ascending alphanumeric ordering. The sort can be reversed by setting the reverse = True argument in the sort function as sort(reverse = True). The values in the list need to be comparable:

temp = [1, 2.3, 3, 2.4, 6, 3, 7]

temp.sort()
print(temp)

temp.sort(reverse=True)
print(temp)

Output:

[1, 2.3, 2.4, 3, 3, 6, 7]
[7, 6, 3, 3, 2.4, 2.3, 1]

The reverse() method on the other hand, simply reverses the order of elements in the list:

temp = [1, 2.3, 3, 2.4, 6, 3, 7]

temp.reverse()
print(temp)

Output: [7, 3, 6, 2.4, 3, 2.3, 1]

sort() method can be applied to the list of strings as well:

colors = ["black", "azure", "ruby", "orange", "blue", "violet", "pink" ]

colors.sort()
print(colors)

Output: ['azure', 'black', 'blue', 'orange', 'pink', 'ruby', 'violet']


The modification operations cannot be performed on a tuple, however, there is a workaround for such cases,