2

If I create a list of tuples lst = [(0,5), (5,0), (2,2)] and use min(lst), it returns (0,5).

How does python decide which tuple to be the smallest?

Is it using first element of tuple to make a decision?

How should I change it to return minimum sum of tuple assuming there are only 2 elements in tuples?

2
  • Possible duplicate of How does the min/max function on a nested list work? Commented Mar 11, 2018 at 0:39
  • @YoungBinJo, if one of the below solutions helped, consider accepting it (green tick on left) so other users know. Commented Mar 22, 2018 at 13:19

1 Answer 1

2

You can use a custom key with min.

lst = [(0,5), (5,0), (2,2)]

res = min(lst, key=lambda x: sum(x))
# (2, 2)

To understand how min(lst) works in general, see How does the min/max function on a nested list work?

If you wish to retrieve element with minimum sum sorted by first element, you can specify a tuple key:

lst2 = [(0,5), (5,0), (2,2), (1,3)]

res = min(lst2, key=lambda x: (sum(x), x[0]))
# (1, 3)

Without using the tuple key, the result above would be (2,2).

Sign up to request clarification or add additional context in comments.

1 Comment

also, first and third element have different sums (5 versus 4).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.