Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One Line Sum List

#1
Python One Line Sum List

<div><p><strong>Article summary:</strong> Here’s a quick visual overview of the contents of this tutorial.</p>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2020/09/pythononelinesumlist-1024x576.jpg" alt="How to sum over all values in a given Python list? " class="wp-image-12551" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/09/pythononelinesumlist-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>
<ul>
<li><strong>Flat List: </strong>To sum over a list of numbers in a single line of Python code, use Python’s built-in function <code>sum(list)</code>.</li>
<li><strong>Nested List: </strong>To sum over a list of lists in one line Python, use a generator expression to flatten the list and pass the result into the function: <code>sum(x for y in list for x in y)</code>. </li>
</ul>
<hr class="wp-block-separator"/>
<h2>Method 1: Sum over a Flat List in One Line</h2>
<p><strong>Problem</strong>: How to sum over all values in a given Python list? </p>
<p><strong>Example</strong>: Given 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 = [1, 2, 3]</pre>
<p>You want to calculate the sum of all values in the list—using only a single line of Python 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=""># RESULT: 6</pre>
<p><strong>Solution</strong>: Python’s built-in <code><a href="https://blog.finxter.com/python-sum-list/" title="Python sum() List – A Simple Illustrated Guide">sum()</a></code> function helps you to sum over all values in an iterable, such as a <a href="https://blog.finxter.com/python-lists/" title="The Ultimate Guide to Python Lists" target="_blank" rel="noreferrer noopener">Python list</a>. </p>
<p>Summing up a list of numbers appears everywhere in coding. Fortunately, Python provides the built-in <code>sum()</code> function to sum over all elements in a Python list—or any other iterable for that matter. <a href="https://docs.python.org/3/library/functions.html#sum" target="_blank" rel="noreferrer noopener">(Official Docs)</a></p>
<p><strong>Code</strong>: Here’s the minimal code 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="">a = [1, 2, 3] print(sum(a))
# 6</pre>
<p>How does it work? The syntax is <code>sum(iterable, start=0)</code>:</p>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>iterable</code></td>
<td>Sum over all elements in the <code>iterable</code>. This can be a list, a tuple, a set, or any other data structure that allows you to iterate over the elements. <br /><strong>Example</strong>: <code>sum([1, 2, 3])</code> returns <code>1+2+3=6</code>. </td>
</tr>
<tr>
<td><code>start</code></td>
<td>(Optional.) The default start value is 0. If you define another start value, the sum of all values in the <code>iterable</code> will be added to this start value. <br /><strong>Example</strong>: <code>sum([1, 2, 3], 9)</code> returns <code>9+1+2+3=15</code>.</td>
</tr>
</tbody>
</table>
</figure>
<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="Python sum() List - A Simple Illustrated Guide" width="1400" height="788" src="https://www.youtube.com/embed/BGddaP8pNcc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Exercise</strong>: Try to modify the sequence so that the sum is 30 in our interactive Python shell:</p>
<p> <iframe src="https://repl.it/@finxter/sumpythonlist?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="600px" frameborder="no"></iframe> </p>
<h2>Method 2: Sum over a Nested List of Lists in One Line</h2>
<p><strong>Problem</strong>: Given multiple lists in a <a href="https://blog.finxter.com/python-list-of-lists/" title="Python List of Lists – A Helpful Illustrated Guide to Nested Lists in Python" target="_blank" rel="noreferrer noopener">list of lists</a>. How can you sum over all values in a list of lists such as <code>[[1, 2], [3, 4], [5, 6]]</code> in Python?</p>
<p><strong>Solution</strong>: Use a <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">generator expression</a> to flatten the values in the nested list and pass the resulting iterable into the <code>sum()</code> function. </p>
<p><strong>Code</strong>: The following code creates a list of lists:</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 = [[1, 2], [3, 4], [5, 6]]</pre>
<p>To sum over the values in the list of lists, use the following <a href="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener" title="https://pythononeliners.com/">one-liner</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="">print(sum(x for y in a for x in y))</pre>
<p>The output is printed on the shell:</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=""># OUTPUT: 21</pre>
<p>But how does it work? The main part of the code is the generator expression <code>x for y in a for x in y</code> that <a href="https://blog.finxter.com/join-list-of-lists/" target="_blank" rel="noreferrer noopener" title="How to Join a List of Lists? You Don’t. You Flatten It!">flattens the list</a>.</p>
<ul>
<li>The part <code>x <strong>for y in a</strong> for x in y</code> iterates over all elements <code>y</code> in the <a href="https://blog.finxter.com/daily-python-puzzle-nested-lists/" target="_blank" rel="noreferrer noopener" title="Nested Lists in Python">nested list </a><code>a</code>. </li>
<li>The part <code>x for y in a <strong>for x in y</strong></code> iterates over all elements <code>y</code> in the inner list <code>y</code>.</li>
<li>The part <code><strong>x</strong> for y in a for x in y</code> stores the inner element in the iterable. </li>
</ul>
<p>Here’s a recap on the technique of <a href="https://blog.finxter.com/list-comprehension/" title="List Comprehension in Python — A Helpful Illustrated Guide" target="_blank" rel="noreferrer noopener">list comprehension</a>. </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="A Simple Introduction to List Comprehension in Python" width="1400" height="788" src="https://www.youtube.com/embed/9qsq2Vf48W8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>To learn more about different ways to sum() elements in a list, check out my detailed blog tutorial:</p>
<p><strong>Related Tutorial</strong>: <a href="https://blog.finxter.com/python-sum-list/" target="_blank" rel="noreferrer noopener" title="Python sum() List – A Simple Illustrated Guide">Python sum() List — Ultimate Guide</a></p>
<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 loading="lazy" 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/...-sum-list/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016