{"id":112533,"date":"2020-05-06T08:56:35","date_gmt":"2020-05-06T08:56:35","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=8255"},"modified":"2020-05-06T08:56:35","modified_gmt":"2020-05-06T08:56:35","slug":"how-to-average-a-list-of-lists-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/05\/06\/how-to-average-a-list-of-lists-in-python\/","title":{"rendered":"How to Average a List of Lists in Python?"},"content":{"rendered":"<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 column average list of lists\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/zUYaG3waoiI?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p><strong>Problem<\/strong>: You have a list of lists and you want to calculate the average of the different columns.<\/p>\n<p><strong>Example<\/strong>: Given the following list of lists with four rows and three columns.<\/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=\"\">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]]<\/pre>\n<p>You want to have the average values of the three columns:<\/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=\"\">[average_col_1, average_col_2, average_col_3]<\/pre>\n<p>There are three methods that solve this problem. You can play with them in the interactive shell and read more details below:<\/p>\n<figure><iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/listoflistsaverage?lite=true\" allowfullscreen=\"true\" width=\"100%\" height=\"1000px\"><\/iframe><\/figure>\n<h2>Method 1: Average in Python (No Library)<\/h2>\n<p>A simple one-liner with <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\">list comprehension<\/a> in combination with the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/zip-unzip-python\/\" target=\"_blank\"><code>zip()<\/code> function<\/a> on the <a href=\"https:\/\/blog.finxter.com\/what-is-asterisk-in-python\/\">unpacked list<\/a> to transpose the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-list-of-lists\/\" target=\"_blank\">list of lists<\/a> does the job in Python. <\/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=\"\">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]] # Method 1: Pure Python\nres = [sum(x) \/ len(x) for x in zip(*data)]\nprint(res)\n# [0.5, 0.75, 0.25]<\/pre>\n<p>Do you love Python one-liners? I do for sure&#8212;I&#8217;ve even written a whole book about it with San Francisco Publisher NoStarch. Click to check out the book in a new tab:<\/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\/04\/3D_transparent-300x277.png\" alt=\"Python One-Liners Book\" class=\"wp-image-7439\" width=\"150\" height=\"139\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/04\/3D_transparent-300x277.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/04\/3D_transparent.png 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/04\/3D_transparent-768x708.png 768w\" sizes=\"auto, (max-width: 150px) 100vw, 150px\" \/><\/a><\/figure>\n<p>You can visualize the code execution and memory objects of this code in the following tool (just click &#8220;Next&#8221; to see how one step of the code unfolds).<\/p>\n<p> <iframe loading=\"lazy\" width=\"800\" height=\"500\" frameborder=\"0\" src=\"https:\/\/pythontutor.com\/iframe-embed.html#code=data%20%3D%20%5B%5B0,%201,%200%5D,%0A%20%20%20%20%20%20%20%20%5B1,%201,%201%5D,%0A%20%20%20%20%20%20%20%20%5B0,%200,%200%5D,%0A%20%20%20%20%20%20%20%20%5B1,%201,%200%5D%5D%0A%0A%0Ares%20%3D%20%5Bsum%28x%29%20\/%20len%28x%29%20for%20x%20in%20zip%28*data%29%5D%0Aprint%28res%29&#038;codeDivHeight=400&#038;codeDivWidth=350&#038;cumulative=false&#038;curInstr=0&#038;heapPrimitives=nevernest&#038;origin=opt-frontend.js&#038;py=3&#038;rawInputLstJSON=%5B%5D&#038;textReferences=false\"> <\/iframe> <\/p>\n<h2>Method 2: Average with NumPy Library<\/h2>\n<p>You create a <a href=\"https:\/\/blog.finxter.com\/numpy-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\">NumPy array<\/a> out of the data and pass it to the <a href=\"https:\/\/blog.finxter.com\/how-to-calculate-weighted-average-numpy-array-along-axis\/\" target=\"_blank\" rel=\"noreferrer noopener\">np.average()<\/a> 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=\"\">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]] # Method 2: NumPy\nimport numpy as np\na = np.array(data)\nres = np.average(a, axis=0)\nprint(res)\n# [0.5 0.75 0.25]<\/pre>\n<p>The <code>axis<\/code> argument of the average function defines along which axis you want to calculate the average value. If you want to average columns, define <code>axis=0<\/code>. If you want to average rows, define <code>axis=1<\/code>. If you want to average over all values, skip this argument. <\/p>\n<h2>Method 3: Mean Statistics Library + Map()<\/h2>\n<p>Just to show you another alternative, here&#8217;s one using the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-get-rid-of-pythons-map-function-with-list-comprehension\/\" target=\"_blank\"><code>map()<\/code> function<\/a> and our <code>zip(*data)<\/code> trick to transpose the &#8220;matrix&#8221; <code>data<\/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=\"\">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]] # Method 3: Statistics + Map()\nimport statistics\nres = map(statistics.mean, zip(*data))\nprint(list(res))\n# [0.5, 0.75, 0.25]<\/pre>\n<p>The <code>map(function, iterable)<\/code> function applies <code>function<\/code> to each element in <code>iterable<\/code>. As an alternative, you can also use <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension-python-list-of-lists\/\" target=\"_blank\">list comprehension<\/a> as shown in method 1 in this tutorial. In fact, Guido van Rossum, the creator of Python and Python&#8217;s benevolent dictator for life (BDFL), <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/about-guidos-fate-of-reduce-in-python-3000\/\" target=\"_blank\">prefers list comprehension over the <code>map()<\/code> function<\/a>. <\/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>\n","protected":false},"excerpt":{"rendered":"<p>Problem: You have a list of lists and you want to calculate the average of the different columns. Example: Given the following list of lists with four rows and three columns. data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]] You want to have the average values of the three [&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-112533","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\/112533","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=112533"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/112533\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=112533"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=112533"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=112533"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}