{"id":117402,"date":"2020-09-01T07:27:45","date_gmt":"2020-09-01T07:27:45","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=12540"},"modified":"2020-09-01T07:27:45","modified_gmt":"2020-09-01T07:27:45","slug":"python-one-line-sum-list","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/09\/01\/python-one-line-sum-list\/","title":{"rendered":"Python One Line Sum List"},"content":{"rendered":"<p><strong>Article summary:<\/strong> Here&#8217;s a quick visual overview of the contents of this tutorial.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" 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\/uploads\/2020\/09\/pythononelinesumlist-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/pythononelinesumlist-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/pythononelinesumlist-150x84.jpg 150w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<ul>\n<li><strong>Flat List: <\/strong>To sum over a list of numbers in a single line of Python code, use Python&#8217;s built-in function <code>sum(list)<\/code>.<\/li>\n<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>\n<\/ul>\n<hr class=\"wp-block-separator\"\/>\n<h2>Method 1: Sum over a Flat List in One Line<\/h2>\n<p><strong>Problem<\/strong>: How to sum over all values in a given Python list? <\/p>\n<p><strong>Example<\/strong>: Given the following 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=\"\">a = [1, 2, 3]<\/pre>\n<p>You want to calculate the sum of all values in the list&#8212;using only a single line of Python 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=\"\"># RESULT: 6<\/pre>\n<p><strong>Solution<\/strong>: Python&#8217;s built-in <code><a href=\"https:\/\/blog.finxter.com\/python-sum-list\/\" title=\"Python sum() List \u2013 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>\n<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>Code<\/strong>: Here&#8217;s the minimal code 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=\"\">a = [1, 2, 3] print(sum(a))\n# 6<\/pre>\n<p>How does it work? The syntax is <code>sum(iterable, start=0)<\/code>:<\/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><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\" 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>\n<h2>Method 2: Sum over a Nested List of Lists in One Line<\/h2>\n<p><strong>Problem<\/strong>: Given multiple lists in a <a href=\"https:\/\/blog.finxter.com\/python-list-of-lists\/\" title=\"Python List of Lists \u2013 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>\n<p><strong>Solution<\/strong>: Use a <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"List Comprehension in Python \u2014 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>\n<p><strong>Code<\/strong>: The following code creates a list of lists:<\/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=\"\">a = [[1, 2], [3, 4], [5, 6]]<\/pre>\n<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>\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=\"\">print(sum(x for y in a for x in y))<\/pre>\n<p>The output is printed on the shell:<\/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=\"\"># OUTPUT: 21<\/pre>\n<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\u2019t. You Flatten It!\">flattens the list<\/a>.<\/p>\n<ul>\n<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>\n<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>\n<li>The part <code><strong>x<\/strong> for y in a for x in y<\/code> stores the inner element in the iterable. <\/li>\n<\/ul>\n<p>Here&#8217;s a recap on the technique of <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\" target=\"_blank\" rel=\"noreferrer noopener\">list comprehension<\/a>. <\/p>\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=\"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>\n<\/div>\n<\/figure>\n<p>To learn more about different ways to sum() elements in a list, check out my detailed blog tutorial:<\/p>\n<p><strong>Related Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-sum-list\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python sum() List \u2013 A Simple Illustrated Guide\">Python sum() List &#8212; Ultimate Guide<\/a><\/p>\n<h2>Python One-Liners Book<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<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\" decoding=\"async\" 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\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<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 &#8220;one-liners&#8221;: concise statements of useful functionality packed into a single line of code. You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;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&#8217;ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You&#8217;ll also learn how to:<\/p>\n<p><strong>\u2022<\/strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br \/><strong>\u2022<\/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>\u2022<\/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>\n<p>By the end of the book, you&#8217;ll know how to write Python at its most refined, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<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>\n","protected":false},"excerpt":{"rendered":"<p>Article summary: Here&#8217;s a quick visual overview of the contents of this tutorial. Flat List: To sum over a list of numbers in a single line of Python code, use Python&#8217;s built-in function sum(list). Nested List: To sum over a list of lists in one line Python, use a generator expression to flatten the list [&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-117402","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\/117402","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=117402"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/117402\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=117402"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=117402"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=117402"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}