Find maximum value and index in a python list?
<p>I have a python list that is like this,</p>

<pre><code>[[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968], [12587982, 0.88], [12587984, 0.8484848484848485], [12587992, 0.7777777777777778], [12587995, 0.8070175438596491], [12588015, 0.4358974358974359], [12588023, 0.8985507246376812], [12588037, 0.5555555555555555], [12588042, 0.9473684210526315]]
</code></pre>

<p>This list can be up to thousand elements in length, how can I get the maximum value in the list according to the second item in the sub-array, and get the index of the maximum value which is the fist element in the sub-array in python?</p>

<p>Use the <a href="https://docs.python.org/3/library/functions.html#max" rel="nofollow"><code>max</code></a> function and its <code>key</code> parameter, to use only the second element to compare elements of the list.</p>

<p>For example,</p>

<pre><code>&gt;&gt;&gt; data = [[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968].... [12588042, 0.9473684210
526315]]
&gt;&gt;&gt; max(data, key=lambda item: item[1])
[12588042, 0.9473684210526315]
</code></pre>

<p>Now, if you want just the first element, then you can simply get the first element alone, or just unpack the result, like this</p>

<pre><code>&gt;&gt;&gt; index, value = max(data, key=lambda item: item[1])
&gt;&gt;&gt; index
12588042
&gt;&gt;&gt; value
0.9473684210526315
</code></pre>

<hr>

<p>Edit: If you want to find the maximum index (first value) out of all elements with the maximum value (second value), then you can do it like this</p>

<pre><code>&gt;&gt;&gt; _, max_value = max(data, key=lambda item: item[1])
&gt;&gt;&gt; max(index for index, value in data if value == max_value)
</code></pre>

<p>You can do the same in a single iteration, like this</p>

<pre><code>max_index = float("-inf")
max_value = float("-inf")

for index, value in data:
      if value &gt; max_value:
          max_value = value
          max_index = index
      elif value == max_value:
          max_index = max(max_index, index)
</code></pre>

python list max