{"id":111930,"date":"2020-04-23T08:27:06","date_gmt":"2020-04-23T08:27:06","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=7831"},"modified":"2020-04-23T08:27:06","modified_gmt":"2020-04-23T08:27:06","slug":"python-sum-list-a-simple-illustrated-guide","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/04\/23\/python-sum-list-a-simple-illustrated-guide\/","title":{"rendered":"Python sum() List \u2013 A Simple Illustrated Guide"},"content":{"rendered":"<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&#8212;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>\n<p><strong>The syntax is <code>sum(iterable, start=0)<\/code>:<\/strong><\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<thead>\n<tr>\n<th>Argument<\/th>\n<th>Description<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><code>iterable<\/code><\/td>\n<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>\n<\/tr>\n<tr>\n<td><code>start<\/code><\/td>\n<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>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<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>\n<p><strong>Code<\/strong>: Let&#8217;s check out a practical example!<\/p>\n<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))\n# 21 print(sum(lst, 10))\n# 31<\/pre>\n<p><strong>Exercise<\/strong>: Try to modify the sequence so that the sum is 30 in our interactive Python shell:<\/p>\n<p> <iframe loading=\"lazy\" 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>\n<p>Let&#8217;s explore some important details regarding the <code>sum()<\/code> function in Python. <\/p>\n<h2>Errors<\/h2>\n<p>A number of errors can happen if you use the <code>sum()<\/code> function in Python.<\/p>\n<p><strong>TypeError<\/strong>: Python will throw a TypeError if you try to sum over elements that are not numerical. Here&#8217;s an example:<\/p>\n<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\nlst = ['Bob', 'Alice', 'Ann'] # WRONG:\ns = sum(lst)<\/pre>\n<p>If you run this code, you&#8217;ll get the following error message:<\/p>\n<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)\nTypeError: unsupported operand type(s) for +: 'int' and 'str'<\/pre>\n<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>\n<p>If you try to &#8220;hack&#8221; Python by using an empty string as start value, you&#8217;ll get the following exception:<\/p>\n<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\nlst = ['Bob', 'Alice', 'Ann'] # WRONG:\ns = sum(lst, '')<\/pre>\n<p>Output:<\/p>\n<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, '')\nTypeError: sum() can't sum strings [use ''.join(seq) instead]<\/pre>\n<p>You can get rid of all those errors by summing only over numerical elements in the list. <\/p>\n<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>\n<h2>Python Sum List Time Complexity<\/h2>\n<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 &#8220;touch&#8221; every iterable element once. <\/p>\n<h2>Python Sum List of Strings<\/h2>\n<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>\n<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>\n<p><strong>Code<\/strong>: The following example shows how to &#8220;sum&#8221; up (i.e., concatenate) all elements in a given list of strings. <\/p>\n<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\nlst = ['Bob', 'Alice', 'Ann'] print(''.join(lst))\n# BobAliceAnn print(' '.join(lst))\n# Bob Alice Ann<\/pre>\n<h2>Python Sum List of Lists<\/h2>\n<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>\n<p><strong>Solution<\/strong>: Use a simple for loop with a helper variable to concatenate all lists.<\/p>\n<p><strong>Code<\/strong>: The following code concatenates all lists into a single list.<\/p>\n<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\nlst = [[1, 2], [3, 4], [5, 6]] s = []\nfor x in lst: s.extend(x)\nprint(s)\n# [1, 2, 3, 4, 5, 6]<\/pre>\n<p>The <code>extend()<\/code> method is little-known in Python&#8212;but it&#8217;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>\n<h2>Python Sum List While Loop<\/h2>\n<p><strong>Problem<\/strong>: How can you sum over all list elements using a while loop (without <code>sum()<\/code>)?<\/p>\n<p><strong>Solution<\/strong>: Create an aggregation variable and iteratively add another element from the list. <\/p>\n<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>\n<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\nlst = [1, 2, 3, 4, 5] # aggregation variable\ns = 0 # index variable\ni = 0 # sum everything up\nwhile i&lt;len(lst): s += lst[i] i += 1 # print the result\nprint(s)\n# 15<\/pre>\n<p>This is not the prettiest way but it&#8217;s readable and it works (and, you didn&#8217;t want to use the <code>sum()<\/code> function, right?). <\/p>\n<h2>Python Sum List For Loop<\/h2>\n<p><strong>Problem<\/strong>: How can you sum over all list elements using a for loop (without <code>sum()<\/code>)?<\/p>\n<p><strong>Solution<\/strong>: Create an aggregation variable and iteratively add another element from the list. <\/p>\n<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>\n<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\nlst = [1, 2, 3, 4, 5] # aggregation variable\ns = 0 # sum everything up\nfor x in lst: s += x # print the result\nprint(s)\n# 15<\/pre>\n<p>This is a bit more readable than the previous version with the while loop because you don&#8217;t have to keep track about the current index. <\/p>\n<h2>Python Sum List with List Comprehension<\/h2>\n<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>\n<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 &#8220;sum&#8221;. <\/p>\n<h2>Python Sum List of Tuples Element Wise<\/h2>\n<p><strong>Problem<\/strong>: How to sum up a list of tuples, element-wise?<\/p>\n<p><strong>Example<\/strong>: Say, you&#8217;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 &#8220;summed tuple&#8221; <code>(1+2+0, 1+0+3)=(3, 4)<\/code>.<\/p>\n<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&#8217;s the code:<\/p>\n<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\nlst = [(1, 1), (2, 0), (0, 3)] # aggregate first and second tuple values\nzipped = list(zip(*lst))\n# result: [(1, 2, 0), (1, 0, 3)] # calculate sum of first and second tuple values\nres = (sum(zipped[0]), sum(zipped[1])) # print result to the shell\nprint(res)\n# result: (3, 4)<\/pre>\n<p>Need a refresher of the <code>zip()<\/code> function and unpacking? Check out these articles on the Finxter blog:<\/p>\n<ul>\n<li><a href=\"https:\/\/blog.finxter.com\/zip-unzip-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">Zip refresher<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/what-is-asterisk-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">Unpacking refresher<\/a><\/li>\n<\/ul>\n<h2>Python Sum List Slice<\/h2>\n<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>\n<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>\n<p><strong>Solution<\/strong>: Use slicing to access the list. Then, apply the sum() function on the result. <\/p>\n<p><strong>Code<\/strong>: The following code computes the sum of a given slice.<\/p>\n<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\nlst = [3, 4, 5, 6, 7, 8, 9, 10] # create the slice\nslc = lst[2:5:2] # calculate the sum\ns = sum(slc) # print the result\nprint(s)\n# 12 (=5+7)<\/pre>\n<p>Let&#8217;s examine an interesting problem: to sum up conditionally!<\/p>\n<h2>Python Sum List Condition<\/h2>\n<p><strong>Problem<\/strong>: Given is a list. How to sum over all values that meet a certain condition?<\/p>\n<p><strong>Example<\/strong>: Say, you&#8217;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>\n<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>\n<p><strong>Code<\/strong>: The following code sums over all values that satisfy a certain condition (e.g., <code>x>4<\/code>). <\/p>\n<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\nlst = [5, 8, 12, 2, 1, 3] # filter the list\nfiltered = [x for x in lst if x>4]\n# remaining list: [5, 8, 12] # sum over the filtered list\ns = sum(filtered) # print everything\nprint(s)\n# 25<\/pre>\n<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>\n<h2>Python Sum List Ignore None<\/h2>\n<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>\n<p><strong>Example<\/strong>: Say, you&#8217;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>\n<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&#8217;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>\n<p><strong>Code<\/strong>: The following code sums over all values that are not <code>None<\/code>. <\/p>\n<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\nlst = [5, None, None, 8, 12, None, 2, 1, None, 3] # filter the list\nfiltered = [x for x in lst if x!=None]\n# remaining list: [5, 8, 12, 2, 1, 3] # sum over the filtered list\ns = sum(filtered) # print everything\nprint(s)\n# 31\n<\/pre>\n<p>A similar thing can be done with the value <code>Nan<\/code> that can disturb your result if you aren&#8217;t careful. <\/p>\n<h2>Python Sum List Ignore Nan<\/h2>\n<p><strong>Problem<\/strong>: Given is a list of numerical values that may contain some values <code>nan<\/code> (=&#8221;not a number&#8221;). How to sum over all values that are not the value <code>nan<\/code>?<\/p>\n<p><strong>Example<\/strong>: Say, you&#8217;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>\n<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&#8217;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>\n<p><strong>Code<\/strong>: The following code sums over all values that are not <code>nan<\/code>. <\/p>\n<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)\nimport math # create the list\nlst = [1, 2, 3, float(\"nan\"), float(\"nan\"), 4] # forget to ignore 'nan'\nprint(sum(lst))\n# nan # ignore 'nan'\nprint(sum([x for x in lst if not math.isnan(x)]))\n# 10<\/pre>\n<p>Phew! Quite some stuff. Thanks for reading through this whole article! I hope you&#8217;ve learned something out of this tutorial and remain with the following recommendation:<\/p>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Summing up a list of numbers appears everywhere in coding. Fortunately, Python provides the built-in sum() function to sum over all elements in a Python list&#8212;or any other iterable for that matter. (Official Docs) The syntax is sum(iterable, start=0): Argument Description iterable Sum over all elements in the iterable. This can be a list, a [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-111930","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/111930","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=111930"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/111930\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=111930"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=111930"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=111930"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}