0

In Python, given a 2d list of the form:

L = [[0, 4],[10, 2],[20, 1],[30, 2]]

How can I obtain the pair that contains the minimum value in the second place? In other words, how to obtain the pair x,y such that y is the smallest among all ys?

That is, in the list above that would be L[2]=[20,1]. I could not find how the min function can be used here.


Edit: I was not able to do a proper search in SO for possible repeated questions. OP agrees to close if needed.

Marion
  • 271
  • 3
  • 11
  • Better dupe target: [Tuple pairs, finding minimum using python](https://stackoverflow.com/questions/14802128/tuple-pairs-finding-minimum-using-python) – gre_gor Jun 06 '22 at 11:54
  • The first comment totally answer my question. I was looking in SO for a while to find this, how did you find it so fast? – Marion Jun 06 '22 at 11:56
  • 1
    Searched for "[python] min tuples" on SO. – gre_gor Jun 06 '22 at 11:57

1 Answers1

1
second_vals = [tup[1] for tup in L]
min_i = second_vals.index(min(second_vals))
print(L[min_i])

Output:

[20,1]

the better way to solve this problem (cleaner and taking O(1) space instead of O(n)) would be to use min with a key function

print(min(L, key=lambda pair: pair[1]))

output:

[20,1]

Hope I could help :)

Ohad Sharet
  • 1,097
  • 9
  • 15