{"id":115030,"date":"2020-07-05T09:41:11","date_gmt":"2020-07-05T09:41:11","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=10466"},"modified":"2020-07-05T09:41:11","modified_gmt":"2020-07-05T09:41:11","slug":"how-to-create-a-python-list-of-size-n","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/05\/how-to-create-a-python-list-of-size-n\/","title":{"rendered":"How to Create a Python List of Size n?"},"content":{"rendered":"<p class=\"has-luminous-vivid-amber-background-color has-background\">To create a list of <code>n<\/code> placeholder elements, multiply the list of a single placeholder element with <code>n<\/code>. For example, use <code>[None] * 5<\/code> to create a list <code>[None, None, None, None, None]<\/code> with five elements <code>None<\/code>. You can then overwrite some elements with index assignments. In the example, <code>lst[2] = 42<\/code> would result in the changed list <code>[None, None, 42, None, None]<\/code>. <\/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=\"How to Create a Python List of Size n?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/d_uBZeKtXSo?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>Let&#8217;s play with an interactive code shell before you&#8217;ll dive into the detailed solution!<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/8b63f214b1\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"400\" frameborder=\"0\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Initialize the list with <code>n=20<\/code> placeholder elements <code>-1<\/code> and run the code. <\/em><\/p>\n<hr class=\"wp-block-separator\"\/>\n<p>Next, you&#8217;ll learn about the more formal problem and dive into the step-by-step solution.<\/p>\n<p><strong>Problem<\/strong>: Given an integer <code>n<\/code>. How to initialize a list with <code>n<\/code> placeholder elements?<\/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=\"\"># n=0 --> []\n# n=1 --> [None]\n# n=5 --> [None, None, None, None, None]<\/pre>\n<p><strong>Solution<\/strong>: Use the list concatenation operation <code>*<\/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=\"\">n = 5\nlst = [None] * n\nprint(lst)\n# [None, None, None, None, None]<\/pre>\n<p>You can modify the element <code>n<\/code> as you like. In subsequent operations, you can overwrite all placeholder <code>None<\/code> list elements using simple index assignment operations:<\/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] = 'Alice'\nlst[1] = 0\nlst[2] = 42\nlst[3] = 12\nlst[4] = 'hello'\nprint(lst)\n# ['Alice', 0, 42, 12, 'hello']<\/pre>\n<p>However, there&#8217;s a small problem if you want to create a list with mutable objects (such as 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>):<\/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 = [[]] * n\nprint(lst)\n# [[], [], [], [], []] lst[2].append(42) print(lst)\n# [[42], [42], [42], [42], [42]]<\/pre>\n<p>Changing one list element changes all list elements because all list elements refer to the same list object in memory:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/pythontutor.com\/iframe-embed.html#code=n%20%3D%205%0Alst%20%3D%20%5B%5B%5D%5D%20*%20n%0Aprint%28lst%29%0A%23%20%5B%5B%5D,%20%5B%5D,%20%5B%5D,%20%5B%5D,%20%5B%5D%5D%0A%0Alst%5B2%5D.append%2842%29%0A%0Aprint%28lst%29%0A%23%20%5B%5B42%5D,%20%5B42%5D,%20%5B42%5D,%20%5B42%5D,%20%5B42%5D%5D&amp;codeDivHeight=400&amp;codeDivWidth=350&amp;cumulative=false&amp;curInstr=1&amp;heapPrimitives=nevernest&amp;origin=opt-frontend.js&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false\" width=\"800\" height=\"500\" frameborder=\"0\"> <\/iframe> <\/p>\n<p>The solution is to use list comprehension (<a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">see my detailed blog tutorial on list comprehension for a complete guide<\/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=\"\">lst = [[] for _ in range(n)]\nprint(lst)\n# [[], [], [], [], []] lst[2].append(42)\nprint(lst)\n# [[], [], [42], [], []]<\/pre>\n<p>In the following visualization, you can see how each element now refers to an independent list object in memory:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/pythontutor.com\/iframe-embed.html#code=n%20%3D%205%0Alst%20%3D%20%5B%5B%5D%20for%20_%20in%20range%28n%29%5D%0Aprint%28lst%29%0A%23%20%5B%5B%5D,%20%5B%5D,%20%5B%5D,%20%5B%5D,%20%5B%5D%5D%0A%0Alst%5B2%5D.append%2842%29%0Aprint%28lst%29%0A%23%20%5B%5B%5D,%20%5B%5D,%20%5B42%5D,%20%5B%5D,%20%5B%5D%5D&amp;codeDivHeight=400&amp;codeDivWidth=350&amp;cumulative=false&amp;curInstr=0&amp;heapPrimitives=nevernest&amp;origin=opt-frontend.js&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false\" width=\"800\" height=\"500\" frameborder=\"0\"> <\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Run the visualization and convince yourself that only one element is modified! Why is this the case?<\/em><\/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>To create a list of n placeholder elements, multiply the list of a single placeholder element with n. For example, use [None] * 5 to create a list [None, None, None, None, None] with five elements None. You can then overwrite some elements with index assignments. In the example, lst[2] = 42 would result in [&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-115030","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\/115030","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=115030"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115030\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=115030"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=115030"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=115030"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}