I have a list of lists, that I want to sort based on the first element of the lists in ascending order. If the first elements of the list are the same, they should be sorted on the basis of the second element.
So far I have been able to sort based on only the first elements of the list. I have used insertion sort for sorting them. How do I sort the list based on second element if first elements are same?
def sort_list ():
# An example of the list to be sorted
original_list = [['Glenn', 'Stevens'],
['Phil', 'Wayne'],
['Peter', 'Martin'],
['Phil', 'Turville'],
['Chris', 'Turville']]
sorted_list = list(original_list)
for index in range(1, len(sorted_list)):
pos = index
while pos > 0 and sorted_list[pos - 1][0] > sorted_list[pos][0]:
sorted_list[pos-1], sorted_list[pos] = sorted_list[pos], sorted_list[pos-1]
pos -= 1
return sorted_list
list.sortalready does this. Usesortedif you don't want to destroyoriginal_listsorted_list = list(original_list)is better written assorted_list = original_list[:]