Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python sorted() Function

#1
Python sorted() Function

<div><p>If you work in a data driven career, odds are you will at some point have to perform sorting on your data. Rather than writing your own sorting algorithm (which will most likely be far less efficient), Python provides a <a href="https://blog.finxter.com/python-built-in-functions/" target="_blank" rel="noreferrer noopener" title="Python Built-In Functions">built-in function</a> called <code>sorted()</code>. This function allows you to do basic sorting, such as arranging in ascending or alphabetical order, but also has the ability for a custom sort, in which you can sort according to your own specifications. </p>
<h2>Definition</h2>
<p>The <code>sorted()</code> function takes a specified iterable input and returns a <a href="https://blog.finxter.com/python-list-sort/" target="_blank" rel="noreferrer noopener" title="Python List sort() – The Ultimate Guide">sorted list</a>. </p>
<p>For example:</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="">>>> x = [4, 1, 2]
>>> sorted(x)
[1, 2, 4]</pre>
<p>It is important to note that the <code>sorted()</code> function does not mutate the original list <code>x</code>; it <a href="https://blog.finxter.com/how-to-create-a-python-list/" target="_blank" rel="noreferrer noopener" title="How to Create a Python List?">creates a new list</a> which can be stored in a separate variable.</p>
<h2>Parameters</h2>
<p>The <code>sorted()</code> function takes at most 3 arguments:</p>
<pre class="wp-block-preformatted"><code><strong>sorted(iterable, key = None, reverse = False)</strong></code></pre>
<ul>
<li><code><strong>iterable</strong></code>: This is the sequence to be sorted. It accepts multiple data types such as a <a href="https://blog.finxter.com/how-to-format-a-string-that-contains-curly-braces-in-python/" target="_blank" rel="noreferrer noopener" title="How To Format A String That Contains Curly Braces In Python?">string</a>, <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list</a>, <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide To Python Tuples">tuple</a>, <a href="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener" title="Python Dictionary – The Ultimate Guide">dictionary </a>etc. and includes <a href="https://blog.finxter.com/python-list-of-lists/" target="_blank" rel="noreferrer noopener" title="Python List of Lists – A Helpful Illustrated Guide to Nested Lists in Python">nested lists</a>. No matter which type of data is entered however, the <code>sorted()</code> function will always return a list.</li>
<li><code>key</code>: This is an optional argument in the <code>sorted()</code> function with the default being <code>None</code>. The key parameter allows you to input a function (built-in or your own function) in order to customise how your list is sorted.</li>
<li><code><strong>reverse</strong></code>: This is an optional argument which indicates whether the data should be sorted in ascending or descending order. The default argument is <code>False</code>, meaning that the data will be sorted in ascending order. </li>
</ul>
<h2>Sorting strings</h2>
<p>When sorting strings, the default is to organise each character in the string in ascending order and return a list of those characters.</p>
<p><strong>Example 1: A single word string</strong></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="">>>> word = 'Python'
>>> sorted(word)
['P', 'h', 'n', 'o', 't', 'y']</pre>
<p><strong>Example 2: A multiple word string</strong></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="">>>> sentence = 'I love Python!'
>>> sorted(sentence)
[' ', ' ', '!' 'I', 'P', 'e', 'h', 'l', 'n', 'o', 'o', 't', 'v', 'y']</pre>
<p>As can be seen in the above example, when the <code>sorted()</code> function is called on a string of multiple words, each character in the string is treated as an element of a list, including the empty spaces. Python orders these elements using the <a href="https://docs.python.org/3/howto/unicode.html" target="_blank" rel="noreferrer noopener">Unicode Standard</a>. What the Unicode Standard does is assign a unique code to every character in all human languages. This allows Python to compare non-numeric characters on a numerical basis as each character has its assigned integer value.</p>
<p>If, however, you want to order a string according to the words in the string rather than according to each character, the <code><a href="https://blog.finxter.com/how-to-split-a-list-into-evenly-sized-chunks/" target="_blank" rel="noreferrer noopener" title="How to Split a List Into Evenly-Sized Chunks?">.split()</a></code> string method can be used.</p>
<p><strong>Example 3: Ordering words in a sentence</strong></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="">>>> phrase = 'The cat in the hat'
>>> sorted(phrase.split())
['The', 'cat', 'hat', 'in', 'the']</pre>
<p><strong>Example 4: Ordering words in a list</strong></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="">>>> words = ['Book', 'Bag', 'pencil', 'basket']
>>> sorted(words)
['Bag', 'Book', 'basket', 'pencil'] </pre>
<p>This example better demonstrates how the Unicode Standard is used. Python orders this data by initially comparing the first letters of each word, and if it finds them to be the same, will move on to compare the second letters and then third and so on. The sorting has put the word ‘Book’ before ‘basket’ telling us that uppercase and lowercase letters do not have the same unicode code point. In general, uppercase letters will have lower code points than the lowercase counterparts, and thus, the words ‘Bag’ and ‘Book’ are placed at the beginning of the list. Since the first letter, ‘B’, is the same in both words, Python goes on to compare the second letters.</p>
<h2>Sorting lists and other complex data types</h2>
<p>As stated previously, when sorting data of all numeric values, the default is to sort the values in ascending order. A new list of ordered values is created which can be stored in a new variable.</p>
<p><strong>Example 1: Sorting a list of numeric values</strong></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="">>>> values = [3, 2, 6, 5]
>>> sorted_values = sorted(values)
>>> print(sorted_values)
[2, 3, 5, 6]</pre>
<p><strong>Example 2: Sorting a tuple of numeric values</strong></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="">>>> numbers = (9, 2, 6, 3, 1)
>>> sorted_numbers = sorted(numbers)
>>> print(sorted_numbers)
[1, 2, 3, 6, 9]</pre>
<p>Take note that, although we inserted a tuple, the <code>sorted()</code> function always returns a list. If desired, you can convert the sorted list into a tuple using the <code>tuple()</code> function and store it in a new variable:</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="">>>> sorted_numbers_tup = tuple(sorted_numbers)
>>> print(sorted_numbers_tup)
(1, 2, 3, 6, 9)</pre>
<p><strong>Example 3: Sorting a dictionary</strong></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="">>>> d = {4: 'a', 3: 'b', 1: 'c'}
>>> sorted(d)
[1, 3, 4]</pre>
<p>Take note that only the dictionary keys are returned in a list because, in order to return both the dictionary key and value, the key argument in the <code>sorted()</code> function will have to be used. This will then return a <a href="https://blog.finxter.com/how-to-sort-a-list-of-tuples-most-pythonic-way/" target="_blank" rel="noreferrer noopener" title="How to Sort a List of Tuples? – Most Pythonic Way!">list of tuple</a>s which can be converted to a <a href="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener" title="Python Dictionary – The Ultimate Guide">dictionary </a>using the function <code>dict()</code>. The usage of keys will be covered later on in this article.</p>
<p><strong>Example 4: Sorting a set</strong></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="">>>> s = {10, 2, 7, 3}
>>> sorted_s = sorted(s)
>>> print(sorted_s)
[2, 3, 7, 10]</pre>
<p>Attempting to convert this ordered list into a set however, will cause you to lose the ordering because a <a href="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Sets – with Harry Potter Examples">set</a>, by definition, is unordered.</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="">>>> set(sorted_s)
{10, 2, 3, 7}</pre>
<p><strong>Example 5: Sorting a nested list</strong></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="">>>> a = [[2, 4], [3, 2], [1, 5], [1, 1]]
>>> sorted(a)
[[1, 1], [1, 5], [2, 4], [3, 2]]</pre>
<p>Here, Python follows the same method as when sorting a list of words. The initial ordering compares the first elements of the <a href="https://blog.finxter.com/python-list-of-lists/" target="_blank" rel="noreferrer noopener" title="Python List of Lists – A Helpful Illustrated Guide to Nested Lists in Python">nested lists</a>. Lists with the same first element are then compared using their second elements and so on. Shorter lists are also placed before longer lists given that their initial elements are the same.</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="">>>> b = [[1, 2, 3], [2, 4], [1, 2]]
>>> sorted(b)
[[1, 2], [1, 2, 3], [2, 4]] </pre>
<h2>Using the key argument </h2>
<p>The key argument in the <code>sorted()</code> function is an extremely useful tool because it allows you to sort the data according to your exact specifications. The function that you input tells Python how you want your data to be ordered. Python applies that function to each element and orders the results. For this you can use one of Python’s extensive built-in functions or create your own function according to your needs.</p>
<p><strong>Example 1: Using an inbuilt function, <code>sum()</code></strong></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="">>>> marks = [[1, 4, 5], [2, 1, 2], [2, 3, 5]]
>>> sorted(marks, key = sum)
[[2, 1, 2], [1, 4, 5], [2, 3, 5]]</pre>
<p>This example orders the nested lists by the <a href="https://blog.finxter.com/python-one-line-sum-list/" target="_blank" rel="noreferrer noopener" title="Python One Line Sum List">sum </a>of each list, smallest to largest, instead of the default to order by elements. </p>
<p><strong>Example 2: Using your own function</strong></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="">>>> def temp(day): return day[1] >>> weather = [['Monday', 25], ['Tuesday', 21], ['Wednesday', 30]]
>>> sorted(weather, key = temp)
[['Tuesday', 21], ['Monday', 25], ['Wednesday', 30]]</pre>
<p>This example demonstrates how you would sort a list according to the second element of each list rather than the first. We first define a function that returns the second element of each list and then use that function as our key. Of course, this is maybe not the most Pythonic way to get this result. The <code>temp()</code> function can be condensed into one line using <a href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank" rel="noreferrer noopener" title="Lambda Functions in Python: A Simple Introduction">lambda</a>.</p>
<p><strong>Example 3: Using lambda in the key</strong></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="">>>> sorted(weather, key = lambda day: day[1])
[['Tuesday', 21], ['Monday', 25], ['Wednesday', 30]]</pre>
<p>Just these few examples demonstrate the power of the key argument.&nbsp;</p>
<h2>Using the reverse argument</h2>
<p>The <code>reverse</code> argument is a fairly simple concept to understand. You use it when you want your data organised in descending instead of ascending order. It takes only a Boolean value, with <code>True</code> referring to descending order and <code>False</code> referring to ascending order. The default, of course, is <code>False</code>. </p>
<p><strong>Example: Sorting in descending order</strong></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="">>>> y = [2, 5, 1, 7]
>>> sorted(y, reverse = True)
[7, 5, 2, 1]</pre>
<p>The same method is used, meaning that the first elements are compared, then the second and so on, to find the largest elements. The reverse argument can be combined with the key argument to create more complex sorts.</p>
<h2>Trying to compare elements of different types</h2>
<p>A limitation of the <code>sorted()</code> function is that it is unable to compare different data types. For example, trying to sort a list that contains both string types and int types results in a <code><a href="https://blog.finxter.com/how-to-solve-python-typeerror-int-object-is-not-iterable/" target="_blank" rel="noreferrer noopener" title="How to Solve Python “TypeError: ‘int’ object is not iterable”?">TypeError</a></code>. This is fairly intuitive; how could we decide what should come first between the elements ‘apples’ and 23. </p>
<p>A comparison that can be done between different types however, is comparing a numeric type (int or <a href="https://blog.finxter.com/decimal-pythons-float-trap-and-how-to-solve-it/" target="_blank" rel="noreferrer noopener" title="Decimal: Python’s Float Trap and How to Solve it">float</a>) with a Boolean type. This is because the two Boolean values each have an inherent numeric value, True has the value 1 and False has the value 0. This means that we can compare lists that have numeric types as well as Boolean expressions as they will evaluate to <code>True</code> or <code>False</code>.</p>
<p>Example:</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="">>>> z = [1, 'A' == 'B', 4 > 3, 0]
>>> sorted(z)
[False, 0, 1, True]</pre>
<h2>Sort stability</h2>
<p>A helpful feature of the <code>sorted()</code> function is something called <strong><em>sort stability</em></strong>. What this means is that if you have an iterable with multiple elements of the same value, they will keep their original order relative to each other. This is very useful when you have two or more iterations through, for example, a list of tuples.</p>
<p>Example:</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="">>>> books_read = [('Steve', 50), ('Dave', 20), ('Fiona', 37), ('Roger', 20)]
>>> sorted(books_read, key = lambda name: name[1])
[('Dave', 20), ('Roger', 20), ('Fiona', 37), ('Steve', 50)]</pre>
<p>In this example, a list of tuples shows how many books each person read in a year. A simple lambda function was used to compare the tuples using the second value in each tuple rather than the first. You can see that Dave and Roger read the same amount of books but when the list was ordered, they kept their position relative to each other.</p>
<h2>Difference between list.sort() and sorted() functions</h2>
<p>As a final note, there is a similar function that exists for the sorting of lists called <code><a href="https://blog.finxter.com/python-list-sort/" target="_blank" rel="noreferrer noopener" title="Python List sort() – The Ultimate Guide">list.sort()</a></code>. It works much the same as the <code>sorted()</code> function, however, there is a key difference between the two. When you call the function <code>list.sort()</code>, it mutates the original list that you are sorting and returns <code>None</code>.</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="">>>> a = [5, 2, 6, 3]
>>> list.sort(a)
>>> a
[2, 3, 5, 6]</pre>
<p>Therefore, when deciding which function to use, it’s important to consider whether you need to keep the original, unordered data. If there is a slight chance you will need it again, the <code>sorted()</code> function is a better option. Not only will it not mutate the original list, but, as mentioned previously, it will accept any iterable, making it a much more powerful function.</p>
<p>For interest’s sake, here is a link to the sorting algorithm used by Python: <a href="https://en.wikipedia.org/wiki/Timsort">Timsort</a> </p>
<hr class="wp-block-separator"/>
<p>To boost your Python skills, download our hand-crafted Python cheat sheets and join our email academy (free):</p>
</p>
<p>The post <a href="https://blog.finxter.com/python-sorted-function/" target="_blank" rel="noopener noreferrer">Python sorted() Function</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/12/...-function/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016