{"id":114968,"date":"2020-07-03T09:39:40","date_gmt":"2020-07-03T09:39:40","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=10409"},"modified":"2020-07-03T09:39:40","modified_gmt":"2020-07-03T09:39:40","slug":"how-to-sort-a-list-of-tuples-most-pythonic-way","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/03\/how-to-sort-a-list-of-tuples-most-pythonic-way\/","title":{"rendered":"How to Sort a List of Tuples? \u2013 Most Pythonic Way!"},"content":{"rendered":"<p>Did you already try to sort a list of tuples? And when you saw the result,<br \/>it wasn&#8217;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>\n<h2>Quick Answer<\/h2>\n<p>Use Python&#8217;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>\n<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)]\nlst.sort(key=lambda x: x[1])<\/pre>\n<h2>How to Sort a List of Tuples by Any Element or Custom Value?<\/h2>\n<p>Let&#8217;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>\n<p>Suppose, we want to sort a list of items like this one:<\/p>\n<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),\n]<\/pre>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/5c5d648b23?start=result\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p>We could either sort the tuples by their first element which is the name, or by their second element, the item&#8217;s price. To achieve this, we could write a custom sort function. But this wouldn&#8217;t be very pythonic.<br \/>Instead we want to use the built-in functions which Python provides. Therefore we have to options:<\/p>\n<ol>\n<li>call sort() on the list (<code>items.sort()<\/code>)<\/li>\n<li>use sorted() to sort the list (<code>sorted_items = sorted(items)<\/code>)<\/li>\n<\/ol>\n<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&#8217;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&#8217;s default: Each tuple&#8217;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&#8217;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>\n<p>To sort the list items by the tuples&#8217; second entry we write:<\/p>\n<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>\n<p>or if you want to preserve the initial order of the items:<\/p>\n<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>\n<p>Our key function takes a tuple x and returns it&#8217;s second entry, thus, the final ordering of the list<br \/>will only take into account each tuple&#8217;s second entry.<br \/>We could also write:<\/p>\n<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>\n<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>\n<p>Finally, it is also important to be aware of Python&#8217;s default behavior for sorting lists of tuples.<br \/>It doesn&#8217;t make sense to write:<\/p>\n<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>\n<p>because this is just what the default behavior does.<\/p>\n<p>To sum it all up, watch this video:<\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<h2>Conclusion<\/h2>\n<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>\n","protected":false},"excerpt":{"rendered":"<p>Did you already try to sort a list of tuples? And when you saw the result,it wasn&#8217;t quiet what you expected? Well, this happend to me when I went deeperinto Python and I suppose, it also happend to you, since you are looking fora solution. This defenitely shows that you are an advanced Python programmer [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-114968","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/114968","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=114968"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/114968\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=114968"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=114968"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=114968"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}