Custom sort function in python

Let’s say we have a list of touples and we want to sort them.
Criteria: If the first element is not equal, then we compare by the first element. Else, we compare by the sum of first and second element.
We can easily do it in C++. But can we do it in Python3 ??

Suppose ‘l’ is your input list of tuples.

l = sorted(l, key = lambda x: (x[0], x[0]+x[1]))

This should work i guess.

3 Likes