Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Sort and Return a Python List in One Line?

#1
How to Sort and Return a Python List in One Line?

<div><p class="has-pale-cyan-blue-background-color has-background">To sort and return a Python list in a single line of code, use the <code>sorted(list)</code> method that returns a new list of sorted elements. It copies only the references to the original elements so the returned list is not a deep but a shallow copy. </p>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/09/sortandreturn-1024x576.jpg" alt="How to Sort and Return a Python List in One Line?" class="wp-image-12570" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/09/sortandreturn-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
</div>
<p>Let’s dive into the challenge to learn about more details and alternatives. Everything is not always simple. By studying the different methods that solves this, you’ll become a better coder!</p>
<p><strong>Problem</strong>: Given a <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list </a>of comparable objects such as integers 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">floats</a>. Is there a way to <a href="https://blog.finxter.com/python-list-sort-key/" target="_blank" rel="noreferrer noopener" title="Python List Sort Key">sort the list</a> and return the sorted list in a <a href="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener">single line of Python</a> code?</p>
<p><strong>Example</strong>: Say, you’ve got the following list.</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 = [4, 2, 1, 3]</pre>
<p>You want to sort this list and return the result in a single line. If you use the <code>list.sort()</code> method, the return value is <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="">print(a.sort())
# None</pre>
<p>The return value of the <code>list.sort()</code> method is <code>None</code>, but many coders expect it to be the sorted list. So they’re surprised finding out that their variables contain the <code>None</code> type rather than a sorted list.</p>
<p>However, returning <code>None</code> makes perfect sense for the <code>list.sort()</code> method. Why? Because you call the method on a list <a href="https://blog.finxter.com/object-oriented-programming-terminology-cheat-sheet/" target="_blank" rel="noreferrer noopener" title="[Python OOP Cheat Sheet] A Simple Overview of Object-Oriented Programming">object </a>and it modifies this exact list object. It doesn’t create a new list—there won’t be a new list object in memory.</p>
<p>So, how to sort and return a list in a single line of Python code? As a rule of thumb, there are always multiple ways to accomplish the same thing in Python. Let’s dive into the different ways to accomplish this!</p>
<p>Here’s a quick overview of the methods addressed in this article:</p>
<p> <iframe src="https://repl.it/@finxter/ModestAllMp3?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="700px" frameborder="no"></iframe> </p>
<p><em><strong>Exercise</strong>: Change the list to be sorted by adding negative floats. Does it still work?</em></p>
<p>You’ll now learn more about each of the methods. </p>
<h2>Method 1: sorted()</h2>
<p>The easiest way to accomplish this task is to call Python’s built-in <code>sorted()</code> function that takes an iterable and returns a new list with sorted elements. </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 = [4, 2, 1, 3] # Method 1: sorted()
print(sorted(a))</pre>
<p>The <code>sorted()</code> function generates a new sorted list that is put into the <code><a href="https://blog.finxter.com/the-separator-and-end-arguments-of-the-python-print-function/" title="Python Print Function [And Its SECRET Separator &amp; End Arguments]">print()</a></code> function that prints the sorted list to the shell. The output is the sorted list:</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="">[1, 2, 3, 4]</pre>
<p>This method is the most <a href="https://blog.finxter.com/whats-the-best-pep8-python-style-checker/" target="_blank" rel="noreferrer noopener" title="What’s the Best PEP8 Python Style Checker?">Pythonic </a>one. But are there alternatives?</p>
<h2>Method 2: list.sort() + Ternary Operator</h2>
<p>The <code>sorted()</code> method leaves the original list unchanged. But what if you want to sort the original list and get this original list as an output that you can assign to a variable?</p>
<p>The answer is simple: use a combination of the <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> method and the <a href="https://blog.finxter.com/python-one-line-ternary/" title="Python One Line Ternary">ternary operator</a>!</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 = [4, 2, 1, 3] # Method 2: list.sort() + ternary
print(a if a.sort() else a)
# [1, 2, 3, 4]</pre>
<p>You need to understand two concepts: (1) <code>list.sort()</code> and (2) the ternary operator:</p>
<ol>
<li>The <code><a href="https://blog.finxter.com/python-list-sort/" title="Python List sort() – The Ultimate Guide" target="_blank" rel="noreferrer noopener">list.sort()</a></code> method sorts the list elements in place in an ascending manner. To customize the default sorting behavior, use the optional <a href="https://blog.finxter.com/python-list-sort-key/" target="_blank" rel="noreferrer noopener" title="Python List Sort Key"><code>key</code> </a>argument by passing a <a href="https://blog.finxter.com/how-to-define-a-function-with-default-arguments-in-python/" target="_blank" rel="noreferrer noopener" title="How to Define a Function with Default Arguments in Python?">function </a>that returns a comparable value for each element in the list.</li>
<li>The <a href="https://blog.finxter.com/python-one-line-ternary/" title="Python One Line Ternary" target="_blank" rel="noreferrer noopener">ternary operator</a> <code>x if c else y</code> consists of three operands <code>x</code>, <code>c</code>, and <code>y</code>. It returns <code>x</code> if the Boolean expression <code>c</code> evaluates to <code>True</code>. Otherwise, if the expression <code>c</code> evaluates to <code>False</code>, the ternary operator returns the alternative <code>y</code>.</li>
</ol>
<p>The beautiful thing is that the <a href="https://blog.finxter.com/python-one-line-x/" title="Python One Line X" target="_blank" rel="noreferrer noopener">one-liner</a> <code>print(a if a.sort() else a)</code> modifies the original list and returns it right away. How does it do this?</p>
<p><strong>Explanation</strong>: First, the <code>a.sort()</code> method is called to check which “branch” of the ternary operator should be visited. The return value of <code>a.sort()</code> will always be <code>None</code>. The <code>None</code> value is automatically converted to the Boolean <code>False</code>. Thus, the ternary operator always returns the list object referred to by variable <code>a</code>. </p>
<p>Note that the only purpose of the ternary operator is to make sure to call the <code>a.sort()</code> method before returning the value <code>a</code>—to make sure it is sorted!</p>
<p>If you print the original list to the shell, you’ll see that it is now sorted:</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="">>>> print(a)
[1, 2, 3, 4]</pre>
<h2>Method 3: Combining Multiple Statements in a Single Line with Semicolon</h2>
<p>An alternative is chaining the statements with a semicolon <code>;</code> to <a href="https://blog.finxter.com/how-to-write-multiple-statements-on-a-single-line-in-python/" title="How to Write Multiple Statements on a Single Line in Python?" target="_blank" rel="noreferrer noopener">one-linerize</a> a Python code snippet. This strategy works with flat Python programs without, possible nested, blocks:</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 = [4, 2, 1, 3] # Method 3: semicolon
a.sort(); print(a)
# [1, 2, 3, 4]</pre>
<p>If you need to sort a Python list and print its return value to the shell—for example because you run this command from the command line or terminal—you can use this excellent strategy. </p>
<p>You can learn more about how to one-linerize any Python program in my following video:</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="[Don't Do This At Home] How To One-Linerize Every Multi-Line Python Script &amp; Run It From The Shell" width="1400" height="788" src="https://www.youtube.com/embed/zGJgctQEkSU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Python One-Liners Book</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<figure class="wp-block-image size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
<p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Python One-Liners</em> </a>will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:</p>
<p><strong>•</strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br /><strong>•</strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br /><strong>•</strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br /><strong>•</strong>&nbsp;&nbsp;Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators<br /><strong>•</strong>&nbsp;&nbsp;Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting</p>
<p>By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners Now!!</em></a></strong></p>
</div>


https://www.sickgaming.net/blog/2020/09/...-one-line/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016