{"id":115067,"date":"2020-07-06T08:14:48","date_gmt":"2020-07-06T08:14:48","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=10516"},"modified":"2020-07-06T08:14:48","modified_gmt":"2020-07-06T08:14:48","slug":"create-a-list-of-random-numbers-the-most-pythonic-way","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/06\/create-a-list-of-random-numbers-the-most-pythonic-way\/","title":{"rendered":"Create a List of Random Numbers \u2014 The Most Pythonic Way"},"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=\"Create a List of Random Numbers \u2014 The Most Pythonic Way\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/b2v2E1bmE-U?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>Do you want to initialize a list with some random numbers? In this article, I&#8217;ll show you four different way of accomplishing this&#8212;along with a short discussion about <em>&#8220;the most Pythonic way&#8221;<\/em>. <\/p>\n<p><strong>Problem<\/strong>: Given an integer <code>n<\/code>. Create a list of <code>n<\/code> elements in a certain interval (example interval: <em>[0, 20]<\/em>). <\/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 --> [2, 3, 1, 4, 3]\n# n = 3 --> [10, 12, 1]\n# n = 10 --> [8, 2, 18, 10, 4, 19, 5, 9, 8, 1]<\/pre>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/random-1024x576.jpg\" alt=\"\" class=\"wp-image-10536\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/random-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/random-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/random-768x432.jpg 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<p><strong>Solution<\/strong>: Here&#8217;s a quick overview on how you can create a list of random numbers:<\/p>\n<ul>\n<li><strong>Method 1<\/strong>: <code>[random.random() for _ in range(10)]<\/code> to create a list of random floats.<\/li>\n<li><strong>Method 2<\/strong>: <code>[random.randint(0, 999) for _ in range(10)]<\/code> to create a list of random ints. <\/li>\n<li><strong>Method 3<\/strong>: <code>randlist = []; for _ in range(10): randlist.append(random.randint(0, 99))<\/code> to create a list of random ints.<\/li>\n<li><strong>Method 4<\/strong>: <code>randlist = random.sample(range(20), 10)<\/code> to create a list of random ints.<\/li>\n<\/ul>\n<p>You can try those yourself in our interactive code shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/4a67c36fc2\" width=\"100%\" height=\"500\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Change the interval of each method to [0, &lt;your age>] and run the code. <\/em><\/p>\n<h2>Method 1: List Comprehension to Random Float List [0, 1]<\/h2>\n<p><a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">List comprehension<\/a> is a compact way of creating lists. The simple formula is <code>[expression + context]<\/code>.<\/p>\n<ul>\n<li><strong>Expression<\/strong>: What to do with each list element?<\/li>\n<li><strong>Context<\/strong>: What elements to select? The context consists of an arbitrary number of <code>for<\/code> and <code>if<\/code> statements.<\/li>\n<\/ul>\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# Method 1: List Comprehension Random Float List [0, 1]\nimport random\nrandlist = [random.random() for _ in range(10)]<\/pre>\n<p>In my Python shell, the result is the following:<\/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(randlist)\n# [0.06472744987876633, 0.011889634172418173, 0.70189711954834, 0.030063483145627568, 0.22255082691969674, 0.26704646386061337, 0.3242939534531408, 0.1781476583083168, 0.5367990394305883, 0.7621210982784024]<\/pre>\n<p>In the code, you first import the random module. <\/p>\n<p>Then, you create a list of random floats by repeatedly calling <code>random.random()<\/code> that generates a random float number between 0 and 1 each time it is called. <\/p>\n<p>You call it ten times as defined in the context part <code>for _ in range(10)<\/code>. Note that the underscore serves as a &#8220;throw-away&#8221; variable as you don&#8217;t actually need it to create the list.<\/p>\n<p>Also note that the list comprehension statement evaluates the expression multiple times&#8212;and not only once in the beginning. That&#8217;s why all the numbers in the list are different. <\/p>\n<p>You can easily extend the creation of floats in a larger interval by multiplying the randomly created float with a constant: <code>[random.random() * 999 for _ in range(10)]<\/code> would create a list of random floats in the interval <code>[0, 999]<\/code>.<\/p>\n<p>If you struggle with understanding list comprehension, watch my explainer video:<\/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>Using list comprehension to generate a list of random numbers is readable, concise, and efficient. Were it not for the fourth method, I&#8217;d consider this to be the most Pythonic way to create a list of random floats. <\/p>\n<h2>Method 2: List Comprehension to Random Integer List [0, 999]<\/h2>\n<p>Just for the sake of completeness, here&#8217;s the list comprehension statement that creates a list of random <em>integers <\/em>in the interval [0, 999]:<\/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# Method 2: List Comprehension Random Int List [0, 999]\nimport random\nrandlist = [random.randint(0, 999) for _ in range(10)]<\/pre>\n<p>In my Python shell, the result is the following:<\/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(randlist)\n# [298, 218, 58, 260, 485, 192, 588, 615, 42, 499]<\/pre>\n<p>You use the <code>random.randint(0, 999)<\/code> function to create a random integer value between start value 0 and end value 999, so all created integers are in the interval [0, 999].<\/p>\n<p>This is a very Pythonic and readable way to create a list of random integers. You can stop reading right away and use it in your own code.<\/p>\n<h2>Method 3: For Loop Random Int List [0, 99]<\/h2>\n<p>An alternative that&#8217;s often used by non-Python coders is to use a <a href=\"https:\/\/blog.finxter.com\/python-loops\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Loops\">simple for loop<\/a> that does the same thing as list comprehension (but demanding more space):<\/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# Method 3: For Loop Random Int List [0, 99]\nimport random\nrandlist = []\nfor _ in range(10): randlist.append(random.randint(0, 99))<\/pre>\n<p>In my Python shell, the result is the following:<\/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(randlist)\n# [19, 35, 0, 13, 36, 15, 13, 65, 41, 99]<\/pre>\n<p>Again, you use the throw-away underscore variable as the random number is not a function of a loop variable. Each two calls to the <code>random.randint()<\/code> function are independent. <\/p>\n<p>I&#8217;d consider this the <em>least <\/em>Pythonic way to solve this problem. <\/p>\n<h2>Method 4: random.sample()<\/h2>\n<p>Finally, we arrive at the most Pythonic way to solve this problem: stand on the shoulders of giants and use existing built-in functionality. The <code>random.sample()<\/code> method takes a &#8220;universe&#8221; from which the random numbers are drawn and a list size <code>n<\/code>&#8212;and draws <code>n<\/code> random numbers from your universe. <\/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# Method 4: random.sample()\nimport random\n# Generate 10 random numbers between 0 and 20 (included)\nrandlist = random.sample(range(20), 10)<\/pre>\n<p>In my Python shell, the result is the following:<\/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(randlist)\n# [1, 3, 0, 14, 7, 9, 13, 4, 12, 8]<\/pre>\n<p>You use the universe <code>range(20)<\/code> of the first 20 integer numbers 0, &#8230;, 19 and draw 10 random elements from the universe. Note that per default, no duplicates are allowed. If the universe is small than the list size n, an error is thrown:<\/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=\"\">ValueError: Sample larger than population or is negative<\/pre>\n<h2>Discussion<\/h2>\n<p>In this tutorial, you&#8217;ve learned four methods to solve the problem of creating a list of random numbers. Objectively, the most Pythonic way to accomplish this is the fourth method: use the <code>random.sample()<\/code> function as it&#8217;s implemented to do exactly this. <\/p>\n<p>But subjectively, I&#8217;d use the first or second method based on list comprehension to create a list of random floats or integers. <\/p>\n<p>Why? Because I&#8217;m lazy and knowing the <code>random.random()<\/code> and <code>random.randint()<\/code> functions is already enough to solve the problem effectively. In practice, I don&#8217;t want to waste too much energy trying to remember code functions that do neither improve readability, nor efficiency of my code. <\/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>Do you want to initialize a list with some random numbers? In this article, I&#8217;ll show you four different way of accomplishing this&#8212;along with a short discussion about &#8220;the most Pythonic way&#8221;. Problem: Given an integer n. Create a list of n elements in a certain interval (example interval: [0, 20]). # n = 5 [&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-115067","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\/115067","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=115067"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115067\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=115067"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=115067"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=115067"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}