Sick Gaming
[Tut] Python sum() List – A Simple Illustrated Guide - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] Python sum() List – A Simple Illustrated Guide (/thread-94704.html)



[Tut] Python sum() List – A Simple Illustrated Guide - xSicKxBot - 04-24-2020

Python sum() List – A Simple Illustrated Guide

<div><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>The syntax is <code>sum(iterable, start=0)</code>:</strong></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><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Check out the <strong>Python Freelancer Webinar</strong> and KICKSTART your coding career!</a></p>
<p><strong>Code</strong>: Let’s check out a practical 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="">lst = [1, 2, 3, 4, 5, 6] print(sum(lst))
# 21 print(sum(lst, 10))
# 31</pre>
<p><strong>Exercise</strong>: Try to modify the sequence so that the sum is 30 in our interactive Python shell:</p>
<p> <iframe height="600px" width="100%" src="https://repl.it/@finxter/sumpythonlist?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<p>Let’s explore some important details regarding the <code>sum()</code> function in Python. </p>
<h2>Errors</h2>
<p>A number of errors can happen if you use the <code>sum()</code> function in Python.</p>
<p><strong>TypeError</strong>: Python will throw a TypeError if you try to sum over elements that are not numerical. Here’s an 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=""># Demonstrate possible execeptions
lst = ['Bob', 'Alice', 'Ann'] # WRONG:
s = sum(lst)</pre>
<p>If you run this code, you’ll get the following error message:</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="">Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 3, in &lt;module> s = sum(lst)
TypeError: unsupported operand type(s) for +: 'int' and 'str'</pre>
<p>Python tries to perform string concatenation using the default start value of 0 (an integer). Of course, this fails. The solution is simple: sum only over numerical values in the list.</p>
<p>If you try to “hack” Python by using an empty string as start value, you’ll get the following exception:</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=""># Demonstrate possible execeptions
lst = ['Bob', 'Alice', 'Ann'] # WRONG:
s = sum(lst, '')</pre>
<p>Output:</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="">Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 5, in &lt;module> s = sum(lst, '')
TypeError: sum() can't sum strings [use ''.join(seq) instead]</pre>
<p>You can get rid of all those errors by summing only over numerical elements in the list. </p>
<p><a rel="noreferrer noopener" href="https://blog.finxter.com/print-python-list/" target="_blank">(For more information about the <code>join()</code> method, check out this blog article.)</a></p>
<h2>Python Sum List Time Complexity</h2>
<p>The time complexity of the <code>sum()</code> function is linear in the number of elements in the iterable (<a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">list</a>, tuple, <a href="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener">set</a>, etc.). The reason is that you need to go over all elements in the iterable and add them to a sum variable. Thus, you need to “touch” every iterable element once. </p>
<h2>Python Sum List of Strings</h2>
<p><strong>Problem</strong>: How can you sum a list of strings such as <code>['python', 'is', 'great']</code>? This is called string concatenation.</p>
<p><strong>Solution</strong>: Use the <code>join()</code> method of Python strings to <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">concatenate all strings</a> in a list. The <code>sum()</code> function works only on numerical input data.</p>
<p><strong>Code</strong>: The following example shows how to “sum” up (i.e., concatenate) all elements in a given list of strings. </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=""># List of strings
lst = ['Bob', 'Alice', 'Ann'] print(''.join(lst))
# BobAliceAnn print(' '.join(lst))
# Bob Alice Ann</pre>
<h2>Python Sum List of Lists</h2>
<p><strong>Problem</strong>: How can you sum a list of lists such as <code>[[1, 2], [3, 4], [5, 6]]</code> in Python?</p>
<p><strong>Solution</strong>: Use a simple for loop with a helper variable to concatenate all lists.</p>
<p><strong>Code</strong>: The following code concatenates all lists into a single 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=""># List of lists
lst = [[1, 2], [3, 4], [5, 6]] s = []
for x in lst: s.extend(x)
print(s)
# [1, 2, 3, 4, 5, 6]</pre>
<p>The <code>extend()</code> method is little-known in Python—but it’s very effective to add a number of elements to a Python list at once. <a href="https://blog.finxter.com/python-list-extend/" target="_blank" rel="noreferrer noopener">Check out my detailed tutorial on this Finxter blog.</a></p>
<h2>Python Sum List While Loop</h2>
<p><strong>Problem</strong>: How can you sum over all list elements using a while loop (without <code>sum()</code>)?</p>
<p><strong>Solution</strong>: Create an aggregation variable and iteratively add another element from the list. </p>
<p><strong>Code</strong>: The following code shows how to sum up all numerical values in a Python list without using the <code>sum()</code> function. </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=""># list of integers
lst = [1, 2, 3, 4, 5] # aggregation variable
s = 0 # index variable
i = 0 # sum everything up
while i&lt;len(lst): s += lst[i] i += 1 # print the result
print(s)
# 15</pre>
<p>This is not the prettiest way but it’s readable and it works (and, you didn’t want to use the <code>sum()</code> function, right?). </p>
<h2>Python Sum List For Loop</h2>
<p><strong>Problem</strong>: How can you sum over all list elements using a for loop (without <code>sum()</code>)?</p>
<p><strong>Solution</strong>: Create an aggregation variable and iteratively add another element from the list. </p>
<p><strong>Code</strong>: The following code shows how to sum up all numerical values in a Python list without using the <code>sum()</code> function. </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=""># list of integers
lst = [1, 2, 3, 4, 5] # aggregation variable
s = 0 # sum everything up
for x in lst: s += x # print the result
print(s)
# 15</pre>
<p>This is a bit more readable than the previous version with the while loop because you don’t have to keep track about the current index. </p>
<h2>Python Sum List with List Comprehension</h2>
<p><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">List comprehension</a> is a powerful Python features that allows you to create a new list based on an existing iterable. Can you sum up all values in a list using only list comprehension? </p>
<p>The answer is no. Why? Because list comprehension exists to create a new list. Summing up values is not about creating a new list. You want to get rid of the list and aggregate all values in the list into a single numerical “sum”. </p>
<h2>Python Sum List of Tuples Element Wise</h2>
<p><strong>Problem</strong>: How to sum up a list of tuples, element-wise?</p>
<p><strong>Example</strong>: Say, you’ve got list <code>[(1, 1), (2, 0), (0, 3)]</code> and you want to sum up the first and the second tuple values to obtain the “summed tuple” <code>(1+2+0, 1+0+3)=(3, 4)</code>.</p>
<p><strong>Solution</strong>: Unpack the tuples into the zip function to combine the first and second tuple values. Then, sum up those values separately. Here’s the 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=""># list of tuples
lst = [(1, 1), (2, 0), (0, 3)] # aggregate first and second tuple values
zipped = list(zip(*lst))
# result: [(1, 2, 0), (1, 0, 3)] # calculate sum of first and second tuple values
res = (sum(zipped[0]), sum(zipped[1])) # print result to the shell
print(res)
# result: (3, 4)</pre>
<p>Need a refresher of the <code>zip()</code> function and unpacking? Check out these articles on the Finxter blog:</p>
<ul>
<li><a href="https://blog.finxter.com/zip-unzip-python/" target="_blank" rel="noreferrer noopener">Zip refresher</a></li>
<li><a href="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank" rel="noreferrer noopener">Unpacking refresher</a></li>
</ul>
<h2>Python Sum List Slice</h2>
<p><strong>Problem</strong>: Given a list. Sum up a slice of the original list between the start and the step indices (and assuming the given step size as well).</p>
<p><strong>Example</strong>: Given is list <code>[3, 4, 5, 6, 7, 8, 9, 10]</code>. Sum up the slice <code>lst[2:5:2]</code> with <code>start=2</code>, <code>stop=5</code>, and <code>step=2</code>. </p>
<p><strong>Solution</strong>: Use slicing to access the list. Then, apply the sum() function on the result. </p>
<p><strong>Code</strong>: The following code computes the sum of a given slice.</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=""># create the list
lst = [3, 4, 5, 6, 7, 8, 9, 10] # create the slice
slc = lst[2:5:2] # calculate the sum
s = sum(slc) # print the result
print(s)
# 12 (=5+7)</pre>
<p>Let’s examine an interesting problem: to sum up conditionally!</p>
<h2>Python Sum List Condition</h2>
<p><strong>Problem</strong>: Given is a list. How to sum over all values that meet a certain condition?</p>
<p><strong>Example</strong>: Say, you’ve got the list <code>lst = [5, 8, 12, 2, 1, 3]</code> and you want to sum over all values that are larger than 4. </p>
<p><strong>Solution</strong>: Use list comprehension to filter the list so that only the elements that satisfy the condition remain. Then, use the <code>sum()</code> function to sum over the remaining values.</p>
<p><strong>Code</strong>: The following code sums over all values that satisfy a certain condition (e.g., <code>x>4</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=""># create the list
lst = [5, 8, 12, 2, 1, 3] # filter the list
filtered = [x for x in lst if x>4]
# remaining list: [5, 8, 12] # sum over the filtered list
s = sum(filtered) # print everything
print(s)
# 25</pre>
<p>Need a refresher on list comprehension? <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">Check out my in-depth tutorial on the Finxter blog. </a></p>
<h2>Python Sum List Ignore None</h2>
<p><strong>Problem</strong>: Given is a list of numerical values that may contain some values <code>None</code>. How to sum over all values that are not the value <code>None</code>?</p>
<p><strong>Example</strong>: Say, you’ve got the list <code>lst = [5, None, None, 8, 12, None, 2, 1, None, 3]</code> and you want to sum over all values that are not <code>None</code>. </p>
<p><strong>Solution</strong>: Use list comprehension to filter the list so that only the elements that satisfy the condition remain (that are different from <code>None</code>). You see, that’s a special case of the previous paragraph that checks for a general condition. Then, use the <code>sum()</code> function to sum over the remaining values.</p>
<p><strong>Code</strong>: The following code sums over all values that are not <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=""># create the list
lst = [5, None, None, 8, 12, None, 2, 1, None, 3] # filter the list
filtered = [x for x in lst if x!=None]
# remaining list: [5, 8, 12, 2, 1, 3] # sum over the filtered list
s = sum(filtered) # print everything
print(s)
# 31
</pre>
<p>A similar thing can be done with the value <code>Nan</code> that can disturb your result if you aren’t careful. </p>
<h2>Python Sum List Ignore Nan</h2>
<p><strong>Problem</strong>: Given is a list of numerical values that may contain some values <code>nan</code> (=”not a number”Wink. How to sum over all values that are not the value <code>nan</code>?</p>
<p><strong>Example</strong>: Say, you’ve got the list <code>lst = [1, 2, 3, float("nan"), float("nan"), 4]</code> and you want to sum over all values that are not <code>nan</code>.</p>
<p><strong>Solution</strong>: Use list comprehension to filter the list so that only the elements that satisfy the condition remain (that are different from <code>nan</code>). You see, that’s a special case of the previous paragraph that checks for a general condition. Then, use the <code>sum()</code> function to sum over the remaining values.</p>
<p><strong>Code</strong>: The following code sums over all values that are not <code>nan</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=""># for checking isnan(x)
import math # create the list
lst = [1, 2, 3, float("nan"), float("nan"), 4] # forget to ignore 'nan'
print(sum(lst))
# nan # ignore 'nan'
print(sum([x for x in lst if not math.isnan(x)]))
# 10</pre>
<p>Phew! Quite some stuff. Thanks for reading through this whole article! I hope you’ve learned something out of this tutorial and remain with the following recommendation:</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p></p>
</div>


https://www.sickgaming.net/blog/2020/04/23/python-sum-list-a-simple-illustrated-guide/