To sort a list of tuples in Python by the second element, you can use the sorted function with a key argument. Here's an example:
main.py122 chars6 lines
Output:
main.py41 chars2 lines
In the example above, we have a list of four tuples with two elements each. We want to sort this list in ascending order based on the second element of each tuple.
We create a new variable called sorted_list and use the sorted function to sort my_list. We pass a lambda function as the key argument, which takes each element x of the list and returns the second element x[1] to be used for sorting.
The result is a new list sorted_list that contains the same tuples as my_list, but sorted in ascending order based on the second element.
gistlibby LogSnag