Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Create a List of Random Numbers — The Most Pythonic Way

#1
Create a List of Random Numbers — The Most Pythonic Way

<div><figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Create a List of Random Numbers — 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>
</div>
</figure>
<p>Do you want to initialize a list with some random numbers? In this article, I’ll show you four different way of accomplishing this—along with a short discussion about <em>“the most Pythonic way”</em>. </p>
<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>
<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 = 3 --> [10, 12, 1]
# n = 10 --> [8, 2, 18, 10, 4, 19, 5, 9, 8, 1]</pre>
<figure class="wp-block-image size-large"><img 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/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p><strong>Solution</strong>: Here’s a quick overview on how you can create a list of random numbers:</p>
<ul>
<li><strong>Method 1</strong>: <code>[random.random() for _ in range(10)]</code> to create a list of random floats.</li>
<li><strong>Method 2</strong>: <code>[random.randint(0, 999) for _ in range(10)]</code> to create a list of random ints. </li>
<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>
<li><strong>Method 4</strong>: <code>randlist = random.sample(range(20), 10)</code> to create a list of random ints.</li>
</ul>
<p>You can try those yourself in our interactive code shell:</p>
<p> <iframe src="https://trinket.io/embed/python/4a67c36fc2" width="100%" height="500" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Change the interval of each method to [0, &lt;your age>] and run the code. </em></p>
<h2>Method 1: List Comprehension to Random Float List [0, 1]</h2>
<p><a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">List comprehension</a> is a compact way of creating lists. The simple formula is <code>[expression + context]</code>.</p>
<ul>
<li><strong>Expression</strong>: What to do with each list element?</li>
<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>
</ul>
<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="">
# Method 1: List Comprehension Random Float List [0, 1]
import random
randlist = [random.random() for _ in range(10)]</pre>
<p>In my Python shell, the result is the following:</p>
<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)
# [0.06472744987876633, 0.011889634172418173, 0.70189711954834, 0.030063483145627568, 0.22255082691969674, 0.26704646386061337, 0.3242939534531408, 0.1781476583083168, 0.5367990394305883, 0.7621210982784024]</pre>
<p>In the code, you first import the random module. </p>
<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>
<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 “throw-away” variable as you don’t actually need it to create the list.</p>
<p>Also note that the list comprehension statement evaluates the expression multiple times—and not only once in the beginning. That’s why all the numbers in the list are different. </p>
<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>
<p>If you struggle with understanding list comprehension, watch my explainer video:</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe 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>
</div>
</figure>
<p>Using list comprehension to generate a list of random numbers is readable, concise, and efficient. Were it not for the fourth method, I’d consider this to be the most Pythonic way to create a list of random floats. </p>
<h2>Method 2: List Comprehension to Random Integer List [0, 999]</h2>
<p>Just for the sake of completeness, here’s the list comprehension statement that creates a list of random <em>integers </em>in the interval [0, 999]:</p>
<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="">
# Method 2: List Comprehension Random Int List [0, 999]
import random
randlist = [random.randint(0, 999) for _ in range(10)]</pre>
<p>In my Python shell, the result is the following:</p>
<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)
# [298, 218, 58, 260, 485, 192, 588, 615, 42, 499]</pre>
<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>
<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>
<h2>Method 3: For Loop Random Int List [0, 99]</h2>
<p>An alternative that’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>
<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="">
# Method 3: For Loop Random Int List [0, 99]
import random
randlist = []
for _ in range(10): randlist.append(random.randint(0, 99))</pre>
<p>In my Python shell, the result is the following:</p>
<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)
# [19, 35, 0, 13, 36, 15, 13, 65, 41, 99]</pre>
<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>
<p>I’d consider this the <em>least </em>Pythonic way to solve this problem. </p>
<h2>Method 4: random.sample()</h2>
<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 “universe” from which the random numbers are drawn and a list size <code>n</code>—and draws <code>n</code> random numbers from your universe. </p>
<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="">
# Method 4: random.sample()
import random
# Generate 10 random numbers between 0 and 20 (included)
randlist = random.sample(range(20), 10)</pre>
<p>In my Python shell, the result is the following:</p>
<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)
# [1, 3, 0, 14, 7, 9, 13, 4, 12, 8]</pre>
<p>You use the universe <code>range(20)</code> of the first 20 integer numbers 0, …, 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>
<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>
<h2>Discussion</h2>
<p>In this tutorial, you’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’s implemented to do exactly this. </p>
<p>But subjectively, I’d use the first or second method based on list comprehension to create a list of random floats or integers. </p>
<p>Why? Because I’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’t want to waste too much energy trying to remember code functions that do neither improve readability, nor efficiency of my code. </p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<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>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


https://www.sickgaming.net/blog/2020/07/...honic-way/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016