{"id":44994,"date":"2023-02-27T21:34:32","date_gmt":"2023-02-27T21:34:32","guid":{"rendered":"https:\/\/www.askpython.com\/?p=44994"},"modified":"2023-02-27T21:34:34","modified_gmt":"2023-02-27T21:34:34","slug":"flattening-nested-lists","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/list\/flattening-nested-lists","title":{"rendered":"Flattening Nested Lists in Python"},"content":{"rendered":"\n<p>Python lists can be nested in the form of 2d structures as a replacement for arrays in other languages. Since python doesn&#8217;t have an array data type, it uses lists to create these 2d, 3d or sometimes N-dimensional arrays. <\/p>\n\n\n\n<p>Flattening refers to the process of reducing <a href=\"https:\/\/www.askpython.com\/python\/array\/multidimensional-arrays\" data-type=\"post\" data-id=\"41390\">2d arrays<\/a> into 1 dimensional list. It collects all the elements from the nested lists and combine them into one list. <\/p>\n\n\n\n<p>There are many ways in which we can convert a list of lists into just one list in python. Let&#8217;s look at some of the methods.<\/p>\n\n\n\n<p><strong><em>If you want to know more about the different data types that are available in python, we have an <a href=\"https:\/\/www.askpython.com\/course\/python-course-datatypes\" data-type=\"URL\" data-id=\"https:\/\/www.askpython.com\/course\/python-course-datatypes\">awesome course for you!<\/a><\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"method-1-using-the-reduce-function\" style=\"text-transform:capitalize\">Method 1: Using the reduce() function<\/h2>\n\n\n\n<p>A built-in function called reduce() can be used to reduce 2d lists into one big list. We have to import the library <a href=\"https:\/\/docs.python.org\/3\/library\/functools.html\" data-type=\"URL\" data-id=\"https:\/\/docs.python.org\/3\/library\/functools.html\" target=\"_blank\" rel=\"noopener\">functools<\/a> in our program in order to use the reduce() function.<\/p>\n\n\n\n<p>If you don&#8217;t have the library installed\/updated, run<code> pip install functools<\/code> in your command prompt. It is a library that contains fast tools for high function programming.<\/p>\n\n\n\n<p>Also , the function <code>concat() <\/code>from the operator module has to be used in addition to the<code> reduce() <\/code>function in order to concatenate the sub-lists into one giant list. The <code>concat()<\/code> function has to be passed as an argument for the reduce() function.<\/p>\n\n\n\n<p>The <code>reduce() <\/code>function takes in two parameters: The first one which defines the concatenation of the inner lists, and the second argument is the required list that needs to be reduced.<\/p>\n\n\n\n<p>Let&#8217;s look at how the function can be used to break down lists of list into one giant list.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#import required modules\nfrom functools import reduce\nfrom operator import concat\n#declaring our list\nlst=&#x5B;&#x5B;1,2],&#x5B;3,4],&#x5B;5,6,7],&#x5B;&#039;bye&#039;,&#039;hi&#039;]]\nprint(&quot;The original list is=&quot;,lst)\n#reducing the list\nflat=reduce(concat,lst)\n#displaying the flattening of the list\nprint(&quot;the reduced list is=&quot;,flat)\n<\/pre><\/div>\n\n\n<p>The output is:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nThe original list is= &#x5B;&#x5B;1, 2], &#x5B;3, 4], &#x5B;5, 6, 7], &#x5B;&#039;bye&#039;, &#039;hi&#039;]]\nthe reduced list is= &#x5B;1, 2, 3, 4, 5, 6, 7, &#039;bye&#039;, &#039;hi&#039;]\n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"455\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-the-reduce-function.-e1677251405151-1024x455.png\" alt=\"Using The Reduce() Function \" class=\"wp-image-45401\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-the-reduce-function.-e1677251405151-1024x455.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-the-reduce-function.-e1677251405151-300x133.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-the-reduce-function.-e1677251405151-768x341.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-the-reduce-function.-e1677251405151.png 1366w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Using The Reduce() Function <\/figcaption><\/figure>\n\n\n\n<p><strong><em><a href=\"https:\/\/www.askpython.com\/python\/built-in-methods\/python-built-in-functions-brief-overview\" data-type=\"URL\" data-id=\"https:\/\/www.askpython.com\/python\/built-in-methods\/python-built-in-functions-brief-overview\">Also read: Python Built-in Functions: Brief Overview.<\/a><\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"method-2-using-nested-loops\" style=\"text-transform:capitalize\">Method 2: Using nested loops<\/h2>\n\n\n\n<p>This method is more mechanical than the previous one. It uses nested for loops to traverse through the individual lists one by one and concatenate each of them into one huge list. Let&#8217;s look at how this can be done.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nlst=&#x5B;&#x5B;&quot;Happy&quot;,&quot;surfing&quot;,&quot;on&quot;],&#x5B;&quot;ask&quot;],&#x5B;&quot;python&quot;]] #the original 2d list\n#displaying original list\nprint(&quot;The original list is =&quot;,lst)\n#creating the flattening list\nflat=&#x5B;]\n#nested loop crreation\nfor i in lst:\n    for j in i:\n        flat.append(j)\n#displaying our results\nprint(&quot;The flattened list is=&quot;,flat)\n<\/pre><\/div>\n\n\n<p>The output of our above code will be:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nThe original list is = &#x5B;&#x5B;&#039;Happy&#039;, &#039;surfing&#039;, &#039;on&#039;], &#x5B;&#039;ask&#039;], &#x5B;&#039;python&#039;]]\nThe flattened list is= &#x5B;&#039;Happy&#039;, &#039;surfing&#039;, &#039;on&#039;, &#039;ask&#039;, &#039;python&#039;]\n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"453\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-nested-for-loops.-e1677252845179-1024x453.png\" alt=\"Using Nested For Loops \" class=\"wp-image-45405\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-nested-for-loops.-e1677252845179-1024x453.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-nested-for-loops.-e1677252845179-300x133.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-nested-for-loops.-e1677252845179-768x340.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-nested-for-loops.-e1677252845179.png 1366w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Using Nested For Loops <\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"method-3-using-list-comprehension-methods\" style=\"text-transform:capitalize\">Method 3: Using list comprehension methods<\/h2>\n\n\n\n<p>In this method we will use the list comprehension methods take make flattening lists easier. It can be done in just one line so let&#8217;s take user input for this example.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nlst=&#x5B;] #the original list and the sublists\n#determining size of list from user input\nN=int(input(&quot;Enter the size of the bigger list=&quot;))\n#taking input\nfor i in range(N):\n  size=int(input(&quot;Enter the size of &quot;+ str(i+1)+&quot; nested list= &quot;))\n  sublst=&#x5B;]\n  for j in range(size):\n    inp=input(&quot;enter the &quot;+str(j+1)+&quot; element of the &quot;+ str(i+1)+&quot; nested list= &quot;)\n    sublst.append(inp)\n  lst.append(sublst)\n#displaying original list\nprint(&quot;The original list is =&quot;,lst)\n#using list comprehension\nflat=&#x5B;element for sublst in lst for element in sublst]\n#displaying our results\nprint(&quot;The flattened list is=&quot;,flat)\n<\/pre><\/div>\n\n\n<p>The output of the above code would be:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nEnter the size of the bigger list=2\nEnter the size of 1 nested list= 2\nenter the 1 element of the 1 nested list= one\nenter the 2 element of the 1 nested list= two\nEnter the size of 2 nested list= 2\nenter the 1 element of the 2 nested list= three\nenter the 2 element of the 2 nested list= four\nThe original list is = &#x5B;&#x5B;&#039;one&#039;, &#039;two&#039;], &#x5B;&#039;three&#039;, &#039;four&#039;]]\nThe flattened list is= &#x5B;&#039;one&#039;, &#039;two&#039;, &#039;three&#039;, &#039;four&#039;]\n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"453\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-list-comprehension-on-user-defined-lists.-e1677252461735-1024x453.png\" alt=\"Using List Comprehension On User Defined Lists \" class=\"wp-image-45403\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-list-comprehension-on-user-defined-lists.-e1677252461735-1024x453.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-list-comprehension-on-user-defined-lists.-e1677252461735-300x133.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-list-comprehension-on-user-defined-lists.-e1677252461735-768x340.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/02\/Using-list-comprehension-on-user-defined-lists.-e1677252461735.png 1366w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Using List Comprehension On User Defined Lists <\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"summary\">Summary<\/h2>\n\n\n\n<p>This tutorial covers three ways in which we flatten a list of lists into one big list. Flattening a list in python is very easy due to a huge availability of resources and <a href=\"https:\/\/www.askpython.com\/python\/built-in-methods\/python-built-in-functions-brief-overview\" data-type=\"post\" data-id=\"32052\">in-built functions<\/a>. Reducing the dimensions of a list can help improve performance and, in some cases, can also simplify calculations. List comprehension is a huge part of python programming. To know more about python lists, <a href=\"https:\/\/developers.google.com\/edu\/python\/lists\" data-type=\"URL\" data-id=\"https:\/\/developers.google.com\/edu\/python\/lists\" target=\"_blank\" rel=\"noopener\">visit the official site<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python lists can be nested in the form of 2d structures as a replacement for arrays in other languages. Since python doesn&#8217;t have an array data type, it uses lists to create these 2d, 3d or sometimes N-dimensional arrays. Flattening refers to the process of reducing 2d arrays into 1 dimensional list. It collects all [&hellip;]<\/p>\n","protected":false},"author":49,"featured_media":45397,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[],"class_list":["post-44994","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-list"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/44994","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/49"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=44994"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/44994\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/45397"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=44994"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=44994"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=44994"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}