When we sort a list it’s sorted by values. If we have a list of tuples, it’s sorted by the first element by default.
1 2 3 4 |
my_list = [(5, 7), (4, 3), (8, 6), (3, 5)] my_list.sort() print('Sorted list:', my_list) |
This code will sort by the first element of a tuple.
Sorted list: [(3, 5), (4, 3), (5, 7), (8, 6)]
Let’s that we want to use a key to sort a list by the second element.
1 2 3 4 5 6 7 8 9 10 |
# takes second element for sort def secondElement(elem): return elem[1] my_list = [(5, 7), (4, 3), (8, 6), (3, 5)] # sorts with a key my_list.sort(key=secondElement) print('Sorted list:', my_list) |
Now, as you can see the second element is used to sort a list. All values are sorted in ascending order: 3, 5, 6, 7.
In a similar way, you can sort a list by the third element:
1 2 3 4 5 6 7 8 9 10 |
# takes second element for sort def thirdElement(elem): return elem[2] my_list = [(5, 7, 4), (4, 3, 8), (8, 6, 2), (3, 5, 1)] # sorts with a key my_list.sort(key=thirdElement) print('Sorted list:', my_list) |
This time the list is sorted by the first element of the tuple elem[2].
Sorted list: [(3, 5, 1), (8, 6, 2), (5, 7, 4), (4, 3, 8)]