sort a list of tuples by the second element in python

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.py
my_list = [(2, 'b'), (1, 'a'), (4, 'd'), (3, 'c')]

sorted_list = sorted(my_list, key=lambda x: x[1])

print(sorted_list)
122 chars
6 lines

Output:

main.py
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
41 chars
2 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