Python 3.x: How do I sort a list of tuples that has the same second element (count) by string value?
<p>So for example</p>

<pre><code>['John','John','Mike','Mike','Kate','Kate']
</code></pre>

<p>Should return:</p>

<pre><code>[('John', 2), ('Kate', 2), ('Mike', 2)]
</code></pre>

<p>How can I write code so there is order instead of those three pairs just being in random order?</p>

<p>I need to sort the list of tuples by count from biggest to smallest unless there are ties, then I need to sort the times alphabetically.</p>

<p>You can sort your result using <code>sorted()</code> function using the <code>key</code> argument to define how to sort the items:</p>

<pre><code>result = [('John', 2), ('Kate', 2), ('Mike', 3)]
sorted_result = sorted(result, key=lambda x: (-x[1], x[0]))
</code></pre>

<p>As you want to sort the result in descending order on the count value and then the name in ascending order, so the key <code>(-x[1], x[0])</code> will do the trick.</p>

<p>The <code>sorted_result</code> will be:</p>

<pre><code>[('Mike', 3), ('John', 2), ('Kate', 2)]
</code></pre>

python python-3.x