Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Sort a List of Tuples? – Most Pythonic Way!

#1
How to Sort a List of Tuples? – Most Pythonic Way!

<div><p>Did you already try to sort a list of tuples? And when you saw the result,<br />it wasn’t quiet what you expected? Well, this happend to me when I went deeper<br />into Python and I suppose, it also happend to you, since you are looking for<br />a solution. This defenitely shows that you are an advanced Python programmer already!</p>
<h2>Quick Answer</h2>
<p>Use Python’s built-in sorted() function or call the method sort() on the list<br />you want to sort. Both of them have an optional parameter key which accepts a<br />function. Pass a function here which computes a key-value from each tuple in the list to sort<br />the tuples by their computed key-values.<br />Example for sorting a list of tuples by their second entry:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = [(1, 2), (2, 3), (0, 3)]
lst.sort(key=lambda x: x[1])</pre>
<h2>How to Sort a List of Tuples by Any Element or Custom Value?</h2>
<p>Let’s first frame our problem in more detail: We have a list of tuples which we want to sort by<br />their second element or sum of elements or anything else which is not the first element of the list.<br />The default behavior of both, sort() and sorted(), is taking the first entry of each tuple to<br />sort the list of tuples. This is what may lead to surprises for beginners.</p>
<p>Suppose, we want to sort a list of items like this one:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">items = [ ("apple", 1.5), ("pear", 2.3), ("egg", 0.5), ("cherry", 0.2),
]</pre>
<p> <iframe src="https://trinket.io/embed/python/5c5d648b23?start=result" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p>We could either sort the tuples by their first element which is the name, or by their second element, the item’s price. To achieve this, we could write a custom sort function. But this wouldn’t be very pythonic.<br />Instead we want to use the built-in functions which Python provides. Therefore we have to options:</p>
<ol>
<li>call sort() on the list (<code>items.sort()</code>)</li>
<li>use sorted() to sort the list (<code>sorted_items = sorted(items)</code>)</li>
</ol>
<p>The difference between the two options is that the first one sorts the list in place and the second one creates a new list instance and adds the sorted items to this new instance. So in both cases you end up with a sorted list. If you need to preserve the list’s initial state use sorted(), in any other case you should prefer calling sort() directly on the list. In both cases the list will be sorted by Python’s default: Each tuple’s first entry.<br />To override the default behavior we use the optional parameter key which is provided by both sort() and sorted(). The parameter key expects a function which can compute a value from a tuple. It is very common to use a lambda to override the default behavior. If you are not yet familiar with Python’s lambdas read all the background knowledge in this <a href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank" rel="noreferrer noopener" title="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/">article</a>.</p>
<p>To sort the list items by the tuples’ second entry we write:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">items.sort(key=lambda x: x[1])</pre>
<p>or if you want to preserve the initial order of the items:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">new_list = sorted(items, key=lambda x: x[1])</pre>
<p>Our key function takes a tuple x and returns it’s second entry, thus, the final ordering of the list<br />will only take into account each tuple’s second entry.<br />We could also write:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">items.sort(key=lambda x: sum(x))</pre>
<p>to sort the tuples by the sum of their entries. Of course, this is not applicable for our example, since the entries of our tuples are strings and integers.</p>
<p>Finally, it is also important to be aware of Python’s default behavior for sorting lists of tuples.<br />It doesn’t make sense to write:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">items.sort(key=lambda x: x[0])</pre>
<p>because this is just what the default behavior does.</p>
<p>To sum it all up, watch this video:</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Coffee Break Python Lambdas - Customize Sort() Method with Lambdas" width="1333" height="1000" src="https://www.youtube.com/embed/FzU8MALxZd8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Conclusion</h2>
<p>Python provides everything you need to sort lists of tuples easily without writing custom sorting functions. All you need to do is define the key-function which computes a value for each tuple by which they should be sorted.</p>
</div>


https://www.sickgaming.net/blog/2020/07/...honic-way/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016