{"id":11799,"date":"2025-01-20T11:22:37","date_gmt":"2025-01-20T11:22:37","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=11799"},"modified":"2025-01-20T11:22:37","modified_gmt":"2025-01-20T11:22:37","slug":"use-lambda-for-sorting-in-python","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/python\/use-lambda-for-sorting-in-python","title":{"rendered":"How to Sort with Lambda in Python"},"content":{"rendered":"<p>In Python, you can use the sorted() function or .sort() method to sort iterables. A lambda function is often used as a key to define custom sorting logic, making it easier to sort data based on specific criteria.<\/p>\n<h3>Example 1: Sorting a List of Dictionaries by a Key<\/h3>\n<p>Let&#8217;s say you have a list of dictionaries, and you want to sort it by a specific key (e.g., &#8220;age&#8221;).<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">data = [\r\n   {'name': 'John', 'age': 25},\r\n   {'name': 'Alice', 'age': 30},\r\n   {'name': 'Bob', 'age': 22}\r\n]\r\n\r\n# Sort by 'age' using lambda function\r\nsorted_data = sorted(data, key=lambda x: x['age'])\r\n\r\nprint(sorted_data);\r\n<\/pre>\n<p><strong>OutPut:-<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\r\n[{'name': 'Bob', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Alice', 'age': 30}]\r\n<\/pre>\n<p>lambda x: x[&#8216;age&#8217;] is used to extract the &#8216;age&#8217; value from each dictionary to determine the sorting order.The key argument specifies the function used to extract the sorting key from each element in the iterable.<\/p>\n<h3>Example 2: Sorting by Multiple Criteria<\/h3>\n<p>You can also use a lambda function to sort by multiple criteria. For example, you might want to sort a list of tuples first by age and then by name.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\r\ndata = [\r\n   ('John', 25),\r\n   ('Alice', 30),\r\n   ('Bob', 22),\r\n   ('Charlie', 25)\r\n]\r\n\r\n# Sort by age first, then by name\r\nsorted_data = sorted(data, key=lambda x: (x[1], x[0]))\r\nprint(sorted_data);\r\n<\/pre>\n<p><strong>Output:-<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\r\n[('Bob', 22), ('John', 25), ('Charlie', 25), ('Alice', 30)]\r\n<\/pre>\n<p>Here, the lambda function returns a tuple (x[1], x[0]), which means the list is sorted by the second element (age) first, and if ages are the same, it sorts by the first element (name).<\/p>\n<h3>Example 3: Sorting in Reverse Order<\/h3>\n<p>If you want to sort in descending order, you can use the reverse=True parameter.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\r\ndata = [5, 3, 8, 1, 2]\r\n\r\n# Sort in descending order\r\nsorted_data = sorted(data, key=lambda x: x, reverse=True)\r\n\r\nprint(sorted_data);\r\n<\/pre>\n<p><strong>Output:-<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\r\n[8, 5, 3, 2, 1]\r\n<\/pre>\n<p>In this example, reverse=True ensures that the list is sorted in descending order.<\/p>\n<p>However, you might encounter issues when trying to use lambda incorrectly. Take below example:<br \/>\n<code>a = sorted(a, lambda x: x.modified, reverse=True)<\/code><\/p>\n<p>The error encountering in above code :<br \/>\n<lambda>() takes exactly 1 argument (2 given)<br \/>\nThis error occurs because sorted() expects the key parameter to be a function that accepts one argument, but the lambda function here isn&#8217;t correctly used.<\/p>\n<p>Issue: The sorted() function&#8217;s key parameter expects a function that takes one argument and returns a value that is used to compare the elements of the iterable.<br \/>\nIn your case, the lambda x: x.modified should be passed as the key argument, but the syntax is incorrect.<\/p>\n<p>Fix: To resolve the issue, you should pass the lambda function correctly as the key argument to sorted(). Here\u2019s the corrected code:<br \/>\n<code>a = sorted(a, key=lambda x: x.modified, reverse=True)<\/code><\/p>\n<p>Explanation: key=lambda x: x.modified tells Python to use the modified attribute of each element in the list a as the sorting criterion.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Python, you can use the sorted() function or .sort() method to sort iterables. A lambda function is often used as a key to define custom sorting logic, making it easier to sort data based on specific criteria. Example 1: Sorting a List of Dictionaries by a Key Let&#8217;s say you have a list of [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":11800,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[16],"tags":[],"class_list":["post-11799","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/11799"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=11799"}],"version-history":[{"count":1,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/11799\/revisions"}],"predecessor-version":[{"id":11801,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/11799\/revisions\/11801"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/11800"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=11799"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=11799"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=11799"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}