{"id":114141,"date":"2020-06-14T18:44:00","date_gmt":"2020-06-14T18:44:00","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=9743"},"modified":"2020-06-14T18:44:00","modified_gmt":"2020-06-14T18:44:00","slug":"how-to-convert-a-list-to-a-numpy-array","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/06\/14\/how-to-convert-a-list-to-a-numpy-array\/","title":{"rendered":"How to Convert a List to a NumPy Array?"},"content":{"rendered":"<p><strong>To convert a Python list to a NumPy array, use either of the following two methods:<\/strong><\/p>\n<ol>\n<li><strong>The <code>np.array()<\/code> function that takes an iterable and returns a NumPy array creating a new data structure in memory<\/strong>.<\/li>\n<li><strong>The <code>np.asarray()<\/code> function that takes an iterable as argument and converts it to the array. The difference to <code>np.array()<\/code> is that <code>np.asarray()<\/code> doesn&#8217;t create a new copy in memory if you pass a NumPy array. All changes made on the original array are reflected on the NumPy array.<\/strong><\/li>\n<\/ol>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/2c445ee795\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Create array <code>b<\/code> from array <code>a<\/code> using both methods. Then change a value in array <code>a<\/code>. What happens at array <code>b<\/code>?<\/em><\/p>\n<h2>NumPy vs Python Lists<\/h2>\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=\"What are Advantages of NumPy over Regular Python Lists?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/MKOw9ATtVqE?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>The Python built-in <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\" rel=\"noreferrer noopener\">list data type<\/a> is powerful. However, the <a href=\"https:\/\/blog.finxter.com\/numpy-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\">NumPy array<\/a> has many advantages over Python lists. What are they?<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<thead>\n<tr>\n<th>Advantages NumPy<\/th>\n<th>Advantages Python Lists<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Multi-dimensional Slicing<\/td>\n<td>Library-Independent<\/td>\n<\/tr>\n<tr>\n<td>Broadcasting Functionality<\/td>\n<td>Intuitive<\/td>\n<\/tr>\n<tr>\n<td>Processing Speed<\/td>\n<td>Less Complicated<\/td>\n<\/tr>\n<tr>\n<td>Memory Footprint<\/td>\n<td>Heterogeneous List Data Allowed<\/td>\n<\/tr>\n<tr>\n<td>Many Convenience Methods<\/td>\n<td>Arbitrary Data Shape (Non-Square Matrix)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p>To read more about the advantages of a NumPy array over a Python list,<a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/what-are-advantages-of-numpy-over-regular-python-lists\/\" target=\"_blank\"> read my detailed blog tutorial.<\/a><\/p>\n<h2>How to Convert a 1D Python List to a NumPy Array?<\/h2>\n<p><strong>Problem<\/strong>: Given a one-dimensional Python list. How to convert it to a NumPy array?<\/p>\n<p><strong>Example<\/strong>: You have the following 1D Python list of integers.<\/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 = [0, 1, 100, 42, 13, 7]<\/pre>\n<p>You want to convert it into a NumPy array.<\/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=\"\">array([ 0, 1, 100, 42, 13, 7])<\/pre>\n<h3>Method 1: np.array(&#8230;)<\/h3>\n<p>The simplest way to convert a Python list to a NumPy array is to use the <code>np.array()<\/code> function that takes an iterable and returns a NumPy array. <\/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=\"\">import numpy as np\nlst = [0, 1, 100, 42, 13, 7]\nprint(np.array(lst))<\/pre>\n<p>The output is:<\/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=\"\"># [ 0 1 100 42 13 7]<\/pre>\n<p>This creates a new data structure in memory. Changes on the original list are not visible to the variable that holds the NumPy array:<\/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 = [0, 1, 100, 42, 13, 7]\na = np.array(lst)\nlst.append(999)\nprint(a)\n# [ 0 1 100 42 13 7]<\/pre>\n<p>The element <code>999<\/code> which is now part of list <code>lst<\/code> is not part of array <code>a<\/code>. <\/p>\n<h3>Method 2: np.asarray(&#8230;)<\/h3>\n<p>An alternative is to use the <code>np.asarray()<\/code> function that takes one argument&#8212;the iterable&#8212;and converts it to the NumPy array. The difference to <code>np.array()<\/code> is that it doesn&#8217;t create a new copy in memory IF you pass a NumPy array. All changes made on the original array are reflected on the NumPy array! So be careful.<\/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 = [0, 1, 100, 42, 13, 7]\na = np.array(lst)\nb = np.asarray(a)\na[0] = 99\nprint(b)\n# [ 99 1 100 42 13 7]<\/pre>\n<p>The array <code>b<\/code> is created using the <code>np.asarray()<\/code> function, so if you change a value of array <code>a<\/code>, the change will be reflected on the variable <code>b<\/code> (because they point to the same object in memory).<\/p>\n<h2>[Video] How to Convert a List of Lists to a NumPy Array?<\/h2>\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=\"How to Convert List of Lists to NumPy Array?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/bnLjhPTw_HU?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<h2>Convert List of Lists to 2D Array<\/h2>\n<p><strong>Problem<\/strong>: Given a <a href=\"https:\/\/blog.finxter.com\/python-list-of-lists\/\" target=\"_blank\" rel=\"noreferrer noopener\">list of lists<\/a> in Python. How to convert it to a 2D <a href=\"https:\/\/blog.finxter.com\/numpy-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\">NumPy array<\/a>?<\/p>\n<p><strong>Example<\/strong>: Convert the following 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=\"\">[[1, 2, 3], [4, 5, 6]]<\/pre>\n<p>into a NumPy array<\/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=\"\">[[1 2 3] [4 5 6]]<\/pre>\n<p><strong>Solution<\/strong>: Use the <code>np.array(list)<\/code> function to convert a list of lists into a two-dimensional NumPy array. 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=\"\"># Import the NumPy library\nimport numpy as np # Create the list of lists\nlst = [[1, 2, 3], [4, 5, 6]] # Convert it to a NumPy array\na = np.array(lst) # Print the resulting array\nprint(a) '''\n[[1 2 3] [4 5 6]] '''<\/pre>\n<p><strong>Try It Yourself<\/strong>: Here&#8217;s the same code in our interactive code interpreter:<\/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=\"\">&lt;iframe height=\"700px\" width=\"100%\" src=\"https:\/\/repl.it\/@finxter\/numpylistoflists?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\">&lt;\/iframe><\/pre>\n<p><strong>Hint<\/strong>: The NumPy method <code>np.array()<\/code> takes an iterable as input and converts it into a NumPy array. <\/p>\n<h2>Convert a List of Lists With Different Number of Elements<\/h2>\n<p><strong>Problem<\/strong>: Given a <a href=\"https:\/\/blog.finxter.com\/copy-list-of-lists-in-python-shallow-vs-deep\/\" target=\"_blank\" rel=\"noreferrer noopener\">list of lists<\/a>. The inner lists have a varying number of elements. How to convert them to a NumPy array?<\/p>\n<p><strong>Example<\/strong>: Say, you&#8217;ve got the following 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=\"\">[[1, 2, 3], [4, 5], [6, 7, 8]]<\/pre>\n<p>What are the different approaches to convert this list of lists into a NumPy array?<\/p>\n<p><strong>Solution<\/strong>: There are three different strategies you can use. (<a rel=\"noreferrer noopener\" href=\"https:\/\/stackoverflow.com\/questions\/10346336\/list-of-lists-into-numpy-array\" target=\"_blank\">source<\/a>) <\/p>\n<p><strong>(1) Use the standard <code>np.array()<\/code> function. <\/strong><\/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=\"\"># Import the NumPy library\nimport numpy as np # Create the list of lists\nlst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array\na = np.array(lst) # Print the resulting array\nprint(a) '''\n[list([1, 2, 3]) list([4, 5]) list([6, 7, 8])] '''<\/pre>\n<p>This creates a NumPy array with three elements&#8212;each element is a list type. You can check the type of the output by using the built-in <code>type()<\/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=\"\">>>> type(a)\n&lt;class 'numpy.ndarray'><\/pre>\n<p><strong>(2) Make an array of arrays.<\/strong><\/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=\"\"># Import the NumPy library\nimport numpy as np # Create the list of lists\nlst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array\na = np.array([np.array(x) for x in lst]) # Print the resulting array\nprint(a) '''\n[array([1, 2, 3]) array([4, 5]) array([6, 7, 8])] '''<\/pre>\n<p>This is more logical than the previous version because it creates a NumPy array of 1D NumPy arrays (rather than 1D Python lists). <\/p>\n<p><strong>(3) Make the lists equal in length.<\/strong><\/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=\"\"># Import the NumPy library\nimport numpy as np # Create the list of lists\nlst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # Calculate length of maximal list\nn = len(max(lst, key=len)) # Make the lists equal in length\nlst_2 = [x + [None]*(n-len(x)) for x in lst]\nprint(lst_2)\n# [[1, 2, 3, None], [4, 5, None, None], [6, 7, 8, 9]] # Convert it to a NumPy array\na = np.array(lst_2) # Print the resulting array\nprint(a) '''\n[[1 2 3 None] [4 5 None None] [6 7 8 9]] '''\n<\/pre>\n<p>You use <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\">list comprehension<\/a> to &#8220;pad&#8221; <code>None<\/code> values to each inner list with smaller than maximal length.<\/p>\n<p>Related Articles<\/p>\n<ul>\n<li><a href=\"https:\/\/blog.finxter.com\/how-to-convert-list-of-lists-to-numpy-array\/\" target=\"_blank\" rel=\"noreferrer noopener\">How to Convert a List of Lists to a NumPy array?<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/what-are-advantages-of-numpy-over-regular-python-lists\/\" target=\"_blank\" rel=\"noreferrer noopener\">What are Advantages of NumPy arrays over Python lists?<\/a><\/li>\n<\/ul>\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>To convert a Python list to a NumPy array, use either of the following two methods: The np.array() function that takes an iterable and returns a NumPy array creating a new data structure in memory. The np.asarray() function that takes an iterable as argument and converts it to the array. The difference to np.array() is [&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-114141","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\/114141","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=114141"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/114141\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=114141"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=114141"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=114141"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}