{"id":3780,"date":"2022-11-02T08:05:15","date_gmt":"2022-11-02T02:35:15","guid":{"rendered":"https:\/\/nolowiz.com\/?p=3780"},"modified":"2022-11-03T07:42:25","modified_gmt":"2022-11-03T02:12:25","slug":"python-list-sorting","status":"publish","type":"post","link":"https:\/\/nolowiz.com\/python-list-sorting\/","title":{"rendered":"Python List Sorting"},"content":{"rendered":"\n<p>Sometimes we might need to sort lists in Python programming. This article will discuss <a href=\"https:\/\/www.python.org\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python <\/a>list sorting methods.<\/p>\n\n\n\n<h2>Using list.sort method<\/h2>\n\n\n\n<p>Python lists have a built-in sort method it modifies the list in place. <\/p>\n\n\n\n<p> <strong>The syntax of the list.sort method<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nsort(*, key=None, reverse=False)\n<\/pre><\/div>\n\n\n<p> <strong>Parameters<\/strong> <\/p>\n\n\n\n<ul><li>key : Callable function that takes a single argument<\/li><li>reverse : a boolean value to indicate comparison in reverse<\/li><\/ul>\n\n\n\n<p>Let&#8217;s see some examples of list.sort method.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nnumbers = &#91;10,1,500,20,70,60,8,122]\nnumbers.sort()\nprint(numbers)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;1, 8, 10, 20, 60, 70, 122, 500]<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<script async src=\"https:\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js?client=ca-pub-2735334721002354\"\n     crossorigin=\"anonymous\"><\/script>\n<!-- article-horizontal -->\n<ins class=\"adsbygoogle\"\n     style=\"display:block\"\n     data-ad-client=\"ca-pub-2735334721002354\"\n     data-ad-slot=\"8835878737\"\n     data-ad-format=\"auto\"\n     data-full-width-responsive=\"true\"><\/ins>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script>\n\n\n\n<p><\/p>\n\n\n\n<p>Reverse sorting by passing <span class=\"has-inline-color has-vivid-red-color\">reverse=True<\/span> to sort method. The list will be sorted in descending order.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nnumbers = &#91;10,1,500,20,70,60,8,122]\nnumbers.sort(reverse=True)\nprint(numbers)\n<\/pre><\/div>\n\n\n<p> <strong>Output<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;500, 122, 70, 60, 20, 10, 8, 1]<\/code><\/pre>\n\n\n\n<h2>Using sorted function<\/h2>\n\n\n\n<p>The sorted built-in function can be used to sort lists.<\/p>\n\n\n\n<p><strong>The syntax of the sorted function <\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nsorted(iterable, key=None, reverse=False)\n<\/pre><\/div>\n\n\n<p>The sorted function has two optional arguments that must be specified as keyword arguments.<\/p>\n\n\n\n<p><strong>Parameters<\/strong><\/p>\n\n\n\n<ul><li><em>key <\/em>: Callable function that takes single argument<\/li><li>r<em>everse<\/em> : a boolean value to indicate comparison in reverse<\/li><\/ul>\n\n\n\n<p><strong>Returns<\/strong><\/p>\n\n\n\n<p> A new sorted list with the items in the iterable<\/p>\n\n\n\n<p>Let&#8217;s see some examples of Python list sorting using the sorted function.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nnumbers = &#91;10,1,500,20,70,60,8,122]\nsorted_nums = sorted(numbers)\nprint(numbers)\nprint(f&quot;Sorted list - {sorted_nums}&quot;)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;10, 1, 500, 20, 70, 60, 8, 122]\nSorted list - &#91;1, 8, 10, 20, 60, 70, 122, 500]]<\/code><\/pre>\n\n\n\n<p><strong>Reverse sort order<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nnumbers = &#91;10,1,500,20,70,60,8,122]\nsorted_nums = sorted(numbers,reverse = True)\nprint(numbers)\nprint(f&quot;Sorted list - {sorted_nums}&quot;)\n<\/pre><\/div>\n\n\n<p> <strong>Output<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;10, 1, 500, 20, 70, 60, 8, 122]\nSorted list - &#91;500, 122, 70, 60, 20, 10, 8, 1<\/code><\/pre>\n\n\n\n<h3>Key functions in sorted\/list.sort()<\/h3>\n\n\n\n<p>The key parameter is a function or callable. The sort function will call the key function on each element before comparison.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nmessage = &quot;This is a test message from NoloWiz&quot;\nsorted_message = sorted(message.split(),key=str.lower)\nprint(sorted_message)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;'a', 'from', 'is', 'message', 'NoloWiz', 'test', 'This']<\/code><\/pre>\n\n\n\n<p>We have used <span class=\"has-inline-color has-vivid-red-color\">str.lower<\/span> as key function.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<script async src=\"https:\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js?client=ca-pub-2735334721002354\"\n     crossorigin=\"anonymous\"><\/script>\n<!-- article-horizontal -->\n<ins class=\"adsbygoogle\"\n     style=\"display:block\"\n     data-ad-client=\"ca-pub-2735334721002354\"\n     data-ad-slot=\"8835878737\"\n     data-ad-format=\"auto\"\n     data-full-width-responsive=\"true\"><\/ins>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script>\n\n\n\n<p><\/p>\n\n\n\n<h3>Sorting tuples<\/h3>\n\n\n\n<p>In this example, we will sort employees&#8217; tuples based on their salary.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nemployees = &#91;\n    ('Tony', 'developer', 1000),\n    ('Robert', 'tester', 800),\n    ('Ram', 'manager', 4000),\n]\n\nemployees_sorted = sorted(employees, key =lambda employee: employee&#91;2]) #sort salary\nprint(employees_sorted)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;('Robert', 'tester', 800), ('Tony', 'developer', 1000), ('Ram', 'manager', 4000)]<\/code><\/pre>\n\n\n\n<h3>Sort class objects<\/h3>\n\n\n\n<p>In this example, we will create a list of objects and sort.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass Employee:\n    def __init__(self, name, desig, salary):\n        self.name = name\n        self.designation = desig\n        self.salary = salary\n\n    def __repr__(self):\n        return repr((self.name, self.designation, self.salary))\n\nemployee_objects = &#91;\n    Employee('Tony', 'developer', 1000),\n    Employee('Robert', 'tester', 800),\n    Employee('Ram', 'manager', 4000),\n]\n\nemployees_sorted = sorted(employee_objects, key=lambda employee: employee.salary)   # sort by salary\nprint(employees_sorted)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;('Robert', 'tester', 800), ('Tony', 'developer', 1000), ('Ram', 'manager', 4000)]<\/code><\/pre>\n\n\n\n<h3>Using itemgetter itemgetter(), attrgetter() with sorting<\/h3>\n\n\n\n<p>The operator module has itemgetter(), attrgetter() funtions,so instead of using lambda expression we can use itemgetter\/attrgetter functions as key function.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom operator import itemgetter, attrgetter\n\nemployees_sorted = sorted(employees, key=itemgetter(2))\nprint(employees_sorted)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;('Robert', 'tester', 800), ('Tony', 'developer', 1000), ('Ram', 'manager', 4000)]<\/code><\/pre>\n\n\n\n<p>Let&#8217;s see an example of object sorting using attrgetter.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom operator import itemgetter, attrgetter\n\nemployees_sorted = sorted(employee_objects, key=attrgetter(&quot;salary&quot;))\nprint(employees_sorted)\n\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;('Robert', 'tester', 800), ('Tony', 'developer', 1000), ('Ram', 'manager', 4000)]<\/code><\/pre>\n\n\n\n<p>Here attrgetter function used to get employee object&#8217;s attribute &#8220;salary&#8221;.<\/p>\n\n\n\n<h2>Conclusion<\/h2>\n\n\n\n<p>These are the different ways to sort lists in Python. <a href=\"https:\/\/nolowiz.com\/python-list-remove-duplicates\/\" target=\"_blank\" rel=\"noreferrer noopener\">Read remove list duplicates<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Sometimes we might need to sort lists in Python programming. This article will discuss Python list sorting methods. Using list.sort method Python lists have a built-in sort method it modifies the list in place. The syntax of the list.sort method Parameters key : Callable function that takes a single argument reverse : a boolean value &#8230; <a title=\"Python List Sorting\" class=\"read-more\" href=\"https:\/\/nolowiz.com\/python-list-sorting\/\" aria-label=\"More on Python List Sorting\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[25],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v16.9 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Python List Sorting - NoloWiz<\/title>\n<meta name=\"description\" content=\"Sometimes we might need to sort lists in Python programming. This article will discuss Python list sorting methods.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/nolowiz.com\/python-list-sorting\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python List Sorting - NoloWiz\" \/>\n<meta property=\"og:description\" content=\"Sometimes we might need to sort lists in Python programming. This article will discuss Python list sorting methods.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/nolowiz.com\/python-list-sorting\/\" \/>\n<meta property=\"og:site_name\" content=\"NoloWiz\" \/>\n<meta property=\"article:published_time\" content=\"2022-11-02T02:35:15+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-11-03T02:12:25+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Rupesh Sreeraman\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Organization\",\"@id\":\"https:\/\/nolowiz.com\/#organization\",\"name\":\"NoloWiz\",\"url\":\"https:\/\/nolowiz.com\/\",\"sameAs\":[],\"logo\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/nolowiz.com\/#logo\",\"inLanguage\":\"en\",\"url\":\"https:\/\/nolowiz.com\/wp-content\/uploads\/2021\/01\/cropped-android-chrome-512x512-2.png\",\"contentUrl\":\"https:\/\/nolowiz.com\/wp-content\/uploads\/2021\/01\/cropped-android-chrome-512x512-2.png\",\"width\":512,\"height\":512,\"caption\":\"NoloWiz\"},\"image\":{\"@id\":\"https:\/\/nolowiz.com\/#logo\"}},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/nolowiz.com\/#website\",\"url\":\"https:\/\/nolowiz.com\/\",\"name\":\"NoloWiz\",\"description\":\"Technology news, tips and tutorials\",\"publisher\":{\"@id\":\"https:\/\/nolowiz.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/nolowiz.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/nolowiz.com\/python-list-sorting\/#webpage\",\"url\":\"https:\/\/nolowiz.com\/python-list-sorting\/\",\"name\":\"Python List Sorting - NoloWiz\",\"isPartOf\":{\"@id\":\"https:\/\/nolowiz.com\/#website\"},\"datePublished\":\"2022-11-02T02:35:15+00:00\",\"dateModified\":\"2022-11-03T02:12:25+00:00\",\"description\":\"Sometimes we might need to sort lists in Python programming. This article will discuss Python list sorting methods.\",\"breadcrumb\":{\"@id\":\"https:\/\/nolowiz.com\/python-list-sorting\/#breadcrumb\"},\"inLanguage\":\"en\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/nolowiz.com\/python-list-sorting\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/nolowiz.com\/python-list-sorting\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/nolowiz.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python List Sorting\"}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/nolowiz.com\/python-list-sorting\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/nolowiz.com\/python-list-sorting\/#webpage\"},\"author\":{\"@id\":\"https:\/\/nolowiz.com\/#\/schema\/person\/6ef6f57a69193ce0993d74a8b6ac4414\"},\"headline\":\"Python List Sorting\",\"datePublished\":\"2022-11-02T02:35:15+00:00\",\"dateModified\":\"2022-11-03T02:12:25+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/nolowiz.com\/python-list-sorting\/#webpage\"},\"wordCount\":297,\"publisher\":{\"@id\":\"https:\/\/nolowiz.com\/#organization\"},\"articleSection\":[\"Python\"],\"inLanguage\":\"en\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/nolowiz.com\/#\/schema\/person\/6ef6f57a69193ce0993d74a8b6ac4414\",\"name\":\"Rupesh Sreeraman\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/nolowiz.com\/#personlogo\",\"inLanguage\":\"en\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/0b6c0696ed1695a540102a80daa94ad0?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/0b6c0696ed1695a540102a80daa94ad0?s=96&d=mm&r=g\",\"caption\":\"Rupesh Sreeraman\"},\"sameAs\":[\"http:\/\/nolowiz.com\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python List Sorting - NoloWiz","description":"Sometimes we might need to sort lists in Python programming. This article will discuss Python list sorting methods.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/nolowiz.com\/python-list-sorting\/","og_locale":"en_US","og_type":"article","og_title":"Python List Sorting - NoloWiz","og_description":"Sometimes we might need to sort lists in Python programming. This article will discuss Python list sorting methods.","og_url":"https:\/\/nolowiz.com\/python-list-sorting\/","og_site_name":"NoloWiz","article_published_time":"2022-11-02T02:35:15+00:00","article_modified_time":"2022-11-03T02:12:25+00:00","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Rupesh Sreeraman","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Organization","@id":"https:\/\/nolowiz.com\/#organization","name":"NoloWiz","url":"https:\/\/nolowiz.com\/","sameAs":[],"logo":{"@type":"ImageObject","@id":"https:\/\/nolowiz.com\/#logo","inLanguage":"en","url":"https:\/\/nolowiz.com\/wp-content\/uploads\/2021\/01\/cropped-android-chrome-512x512-2.png","contentUrl":"https:\/\/nolowiz.com\/wp-content\/uploads\/2021\/01\/cropped-android-chrome-512x512-2.png","width":512,"height":512,"caption":"NoloWiz"},"image":{"@id":"https:\/\/nolowiz.com\/#logo"}},{"@type":"WebSite","@id":"https:\/\/nolowiz.com\/#website","url":"https:\/\/nolowiz.com\/","name":"NoloWiz","description":"Technology news, tips and tutorials","publisher":{"@id":"https:\/\/nolowiz.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/nolowiz.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en"},{"@type":"WebPage","@id":"https:\/\/nolowiz.com\/python-list-sorting\/#webpage","url":"https:\/\/nolowiz.com\/python-list-sorting\/","name":"Python List Sorting - NoloWiz","isPartOf":{"@id":"https:\/\/nolowiz.com\/#website"},"datePublished":"2022-11-02T02:35:15+00:00","dateModified":"2022-11-03T02:12:25+00:00","description":"Sometimes we might need to sort lists in Python programming. This article will discuss Python list sorting methods.","breadcrumb":{"@id":"https:\/\/nolowiz.com\/python-list-sorting\/#breadcrumb"},"inLanguage":"en","potentialAction":[{"@type":"ReadAction","target":["https:\/\/nolowiz.com\/python-list-sorting\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/nolowiz.com\/python-list-sorting\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/nolowiz.com\/"},{"@type":"ListItem","position":2,"name":"Python List Sorting"}]},{"@type":"Article","@id":"https:\/\/nolowiz.com\/python-list-sorting\/#article","isPartOf":{"@id":"https:\/\/nolowiz.com\/python-list-sorting\/#webpage"},"author":{"@id":"https:\/\/nolowiz.com\/#\/schema\/person\/6ef6f57a69193ce0993d74a8b6ac4414"},"headline":"Python List Sorting","datePublished":"2022-11-02T02:35:15+00:00","dateModified":"2022-11-03T02:12:25+00:00","mainEntityOfPage":{"@id":"https:\/\/nolowiz.com\/python-list-sorting\/#webpage"},"wordCount":297,"publisher":{"@id":"https:\/\/nolowiz.com\/#organization"},"articleSection":["Python"],"inLanguage":"en"},{"@type":"Person","@id":"https:\/\/nolowiz.com\/#\/schema\/person\/6ef6f57a69193ce0993d74a8b6ac4414","name":"Rupesh Sreeraman","image":{"@type":"ImageObject","@id":"https:\/\/nolowiz.com\/#personlogo","inLanguage":"en","url":"https:\/\/secure.gravatar.com\/avatar\/0b6c0696ed1695a540102a80daa94ad0?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/0b6c0696ed1695a540102a80daa94ad0?s=96&d=mm&r=g","caption":"Rupesh Sreeraman"},"sameAs":["http:\/\/nolowiz.com"]}]}},"_links":{"self":[{"href":"https:\/\/nolowiz.com\/wp-json\/wp\/v2\/posts\/3780"}],"collection":[{"href":"https:\/\/nolowiz.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nolowiz.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nolowiz.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nolowiz.com\/wp-json\/wp\/v2\/comments?post=3780"}],"version-history":[{"count":59,"href":"https:\/\/nolowiz.com\/wp-json\/wp\/v2\/posts\/3780\/revisions"}],"predecessor-version":[{"id":3864,"href":"https:\/\/nolowiz.com\/wp-json\/wp\/v2\/posts\/3780\/revisions\/3864"}],"wp:attachment":[{"href":"https:\/\/nolowiz.com\/wp-json\/wp\/v2\/media?parent=3780"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nolowiz.com\/wp-json\/wp\/v2\/categories?post=3780"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nolowiz.com\/wp-json\/wp\/v2\/tags?post=3780"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}