{"id":2393,"date":"2020-01-09T06:27:32","date_gmt":"2020-01-09T06:27:32","guid":{"rendered":"https:\/\/www.askpython.com\/?p=2393"},"modified":"2023-01-19T18:26:03","modified_gmt":"2023-01-19T18:26:03","slug":"python-sort-list","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/list\/python-sort-list","title":{"rendered":"Python sort() Method: How to perform Python List Sorting"},"content":{"rendered":"\n<p>Python\u2019s list sort() method is used to sort a list in either ascending or descending order, additionally, you can also define the criteria to sort.\u00a0<\/p>\n\n\n\n<p>This tutorial will provide a complete guide to all types of list sorting in Python using the sort() method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Overview of List Sorting&nbsp;<\/h2>\n\n\n\n<p>Sorting is a technique to rearrange items. Arranging the elements of a list in a certain order, such as accessing or descending based on given criteria, is referred to as sorting.<\/p>\n\n\n\n<p>A real-life example is the student records which it is required to arrange in ascending order by name.<\/p>\n\n\n\n<p>Imagine, a school containing hundreds of records of students in a python list, and new students are continually being added, it can be difficult to maintain the order. In situations like this, sorting can be used to organize the list by arranging the records in ascending order based on the name criteria.<\/p>\n\n\n\n<p>A list can directly sort using the sort() method.&nbsp;We have a separate article on <a href=\"https:\/\/www.askpython.com\/python\/list\/python-list\" data-type=\"URL\" data-id=\"https:\/\/www.askpython.com\/python\/list\/python-list\" target=\"_blank\" rel=\"noreferrer noopener\">Python List<\/a> if you want to read it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">sort() Method<\/h2>\n\n\n\n<p>This method takes two arguments, the first is <strong><code><strong>reverse<\/strong><\/code> <\/strong>, and the second is a <strong><code>key<\/code><\/strong>.<\/p>\n\n\n\n<p>The <strong><code>reverse<\/code> <\/strong>accepts a boolean value(i.e. True or False) that decides whether to sort a list in ascending or descending order, to sort in descending order the value should be True and for ascending the value should be False. By default value is False, if you want to sort a list in ascending order you don\u2019t have to pass this argument, as it is the default.<\/p>\n\n\n\n<p>The <strong><code>key<\/code><\/strong> accepts a function that decides the sort criteria such as on the based of a particular field, on the bases of the length of objects, etc.<\/p>\n\n\n\n<p>Syntax:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nlist_name.sort(reverse=True|False, key=function)\n<\/pre><\/div>\n\n\n<p>where,<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>list_name <\/strong>is the name of the list you want to sort,<\/li>\n\n\n\n<li><strong>reverse <\/strong>can be true or false,<\/li>\n\n\n\n<li><strong>function <\/strong>can be any function to decide the sort criteria<\/li>\n<\/ul>\n\n\n\n<p><strong>Note:<\/strong> The sort() method does not return a new list, it sorts the actual list, so if you use a sort method, you no longer have the access to the actual list order.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Techniques to Sort a List in Python<\/h2>\n\n\n\n<p>Here are a few norms for using the sort() method to sort a list:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Sort the List in Ascending Order<\/strong><\/li>\n\n\n\n<li><strong>Sort the List in Descending Order<\/strong><\/li>\n\n\n\n<li><strong>Sort the List using a Key<\/strong><\/li>\n\n\n\n<li><strong>Sort the List using User-defined Orde<\/strong>r<\/li>\n\n\n\n<li><strong>Sort the List of Objects<\/strong><\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s examine each of them separately<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Sort the List Elements in Ascending Order<\/h3>\n\n\n\n<p>Ascending refers to arranging the lowest value on the left side and increasing toward the highest value on the right side.<\/p>\n\n\n\n<p>To sort a list in ascending order, the value passes to the reverse parameter should be False, since the default value is also False we don\u2019t have to pass any parameter.<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<p>Here we created a list containing floating point numbers, then used the sort method without passing any additional parameter, and printed the list.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ninput = &#x5B;1.2, 221, 0.025, 0.124, 1.2]\n\nprint(f&#039;Before: {input}&#039;)\n\ninput.sort()\n\nprint(f&#039;After: {input}&#039;)\n\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Before : &#91;1.2, 221, 0.025, 0.124, 1.2]\nAfter : &#91;0.025, 0.124, 1.2, 1.2, 221]<\/code><\/pre>\n\n\n\n<p>In the above output, you can see that the list values are sorted in ascending order.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Sort the List Elements in Descending Order<\/h3>\n\n\n\n<p>Descending refers to arranging the highest value on the left side and decreasing toward the lowest value on the right side.<\/p>\n\n\n\n<p>To sort a list in descending order, the value passed to the reverse parameter should be True.<\/p>\n\n\n\n<p><strong>Syntax: <\/strong> <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nlist_name.sort(reverse=True)\n<\/pre><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<p>Here we created a list containing numbers, then used the sort method, passed an additional parameter \u201creverse=True\u201d to sort the list in descending order, and printed the list.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ninput = &#x5B;8, 1, 12, 0]\n\ninput.sort(reverse = True)\n\nprint(input)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;12, 8, 1, 0]<\/code><\/pre>\n\n\n\n<p>In the above output, you can see that the list values are sorted in descending order.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. Sort the List using a Key Function<\/h3>\n\n\n\n<p>A list can sort on the bases of some predefined order. It is required to create a function that defines the criteria, and then pass the name of that function to the key parameter inside the sort() method.&nbsp;&nbsp;<\/p>\n\n\n\n<p>Let\u2019s see an example for more clearance.<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<p>Here we have defined a function that returns the third element of the values of the list, this function has then passed as a key to the sort() method to sort based on the third element of the values.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# takes third element for sort\ndef third_element(x):\n    return x&#x5B;2]\n\n\ninput = &#x5B;(2, 2, 1), (3, 4, 9), (4, 1, 0), (1, 3, 7)]\n\n# sort list with key\ninput.sort(key=third_element)\n\n# prints sorted list\nprint(&#039;Sorted list:&#039;, input)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Sorted list: &#91;(4, 1, 0), (2, 2, 1), (1, 3, 7), (3, 4, 9)]<\/code><\/pre>\n\n\n\n<p>The above output shows that the list values are sorted in ascending order of their third element.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. Sort the List using User-defined Order<\/h3>\n\n\n\n<p>Again, we can use the key parameter to pass a function to define our own sort order.<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# takes third element for sort\ndef third_element(x):\n    return x&#x5B;2]\n\n\ninput = &#x5B;(2, 2, 1), (3, 4, 9), (4, 1, 0), (1, 3, 7)]\n\n# sorts list with key in ascending order\ninput.sort(key=third_element)\n\n# prints sorted list\nprint(&#039;Sorted list in ascending order:&#039;, input)\n\n# sorts list with key in descending order\ninput.sort(key=third_element, reverse=True)\n\nprint(&#039;Sorted list in descending order:&#039;, input)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Sorted list in ascending order: &#91;(4, 1, 0), (2, 2, 1), (1, 3, 7), (3, 4, 9)]\nSorted list in descending order: &#91;(3, 4, 9), (1, 3, 7), (2, 2, 1), (4, 1, 0)]<\/code><\/pre>\n\n\n\n<p>The above output shows that the list values are sorted in ascending and descending order of their third element.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5. Sort the List of Class Objects<\/h3>\n\n\n\n<p>In order to sort the list of custom objects using the sort() function, you need to define the key function specifying the object\u2019s field, based on which you want to sort the list elements.<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass Details:\n\n    def __init__(self, name, num):\n        self.name = name\n        self.num = num\n\n\n    def __str__(self):\n        return f&#039;Details&#x5B;{self.name}:{self.num}]&#039;\n\n\n    __repr__ = __str__\n\n\nD1 = Details(&#039;Safa&#039;, 12)\nD2 = Details(&#039;Aman&#039;, 1)\nD3 = Details(&#039;Shalini&#039;, 45)\nD4 = Details(&#039;Ruh&#039;, 30)\n\ninput_list = &#x5B;D1, D2, D3, D4]\n\nprint(f&#039;Before Sorting: {input_list}&#039;)\n\n\n\ndef sort_by_num(details):\n    return details.num\n\n\ninput_list.sort(key=sort_by_num)\nprint(f&#039;After Sorting By Number: {input_list}&#039;)\n<\/pre><\/div>\n\n\n<p>In the above code example, we have created a class, and from that class, we have created multiple objects and passed them inside a list, and printed that list, you can see that the list printed has all the objects.<\/p>\n\n\n\n<p>In order to sort its object we then defined a function, notice how we defined the return value to be a specific object\u2019s field(num), which will be the criteria for sort. After passing the function to the sort method, we again printed the list.&nbsp;<\/p>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Before Sorting: &#91;Details&#91;Safa:12], Details&#91;Aman:1], Details&#91;Shalini:45], Details&#91;Ruh:30]]\nAfter Sorting By Number: &#91;Details&#91;Aman:1], Details&#91;Safa:12], Details&#91;Ruh:30], Details&#91;Shalini:45]]<\/code><\/pre>\n\n\n\n<p>You can see that the list object is sorted in ascending order to their num field. Hence the output is justified.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this tutorial, we have explained the sort() method which is used to sort a list in python. This method takes two arguments, the first one is <strong>&#8220;reverse&#8221; <\/strong>which contains a boolean value that defines the sort order, where False represents ascending order and True represents descending order. The second argument is a <strong>&#8220;key&#8221;<\/strong> which contains a function that defines the criteria to sort, such as based on some field, length, etc. <\/p>\n\n\n\n<p>We have also covered the different approaches to this method to sort, such as in ascending order, descending order, on the basis of custom or user-defined criteria, etc. We also discussed the process to sort a list of class objects. Hope this tutorial helps you to sort the list in python.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<p><a class=\"rank-math-link rank-math-link\" href=\"https:\/\/docs.python.org\/3.3\/howto\/sorting.html\" target=\"_blank\" rel=\"noopener\">Sorting documentation<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python\u2019s list sort() method is used to sort a list in either ascending or descending order, additionally, you can also define the criteria to sort.\u00a0 This tutorial will provide a complete guide to all types of list sorting in Python using the sort() method. Overview of List Sorting&nbsp; Sorting is a technique to rearrange items. [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":39722,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[480],"class_list":["post-2393","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-list","tag-python-sort-list"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/2393","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=2393"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/2393\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/39722"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=2393"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=2393"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=2393"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}