Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python range() Function — A Helpful Illustrated Guide

#1
Python range() Function — A Helpful Illustrated Guide

<div><p class="has-pale-cyan-blue-background-color has-background">The Python <code>range()</code> function creates an iterable of subsequent integers within a given range of values. You can pass either only a <code>stop</code> argument in which case the <code>range</code> object will include all integers from <code>0</code> to <code>stop</code> (excluded). Or you can pass <code>start</code>, <code>stop</code>, and <code>step</code> arguments in which case the range object will go from <code>start</code> to <code>step</code> using the given <code>step</code> size. For example, <code>range(3)</code> results in <code>0, 1, 2</code> and <code>range(2, 7, 2)</code> results in <code>2, 4, 6</code>. </p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python range() Function | A Helpful Illustrated Guide" width="1400" height="788" src="https://www.youtube.com/embed/vcu2Q-6sr-Q?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<hr class="wp-block-separator"/>
<p>Here are some examples of how to use the <code>range()</code> <a href="https://blog.finxter.com/python-built-in-functions/" title="Python Built-In Functions">built-in function</a>:</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="">>>> range(10)
range(0, 10)
>>> print(range(10))
range(0, 10)
>>> print(*range(10))
0 1 2 3 4 5 6 7 8 9
>>> range(1, 10, 3)
range(1, 10, 3)
>>> print(*range(1, 10, 3))
1 4 7</pre>
<p>Note that in any case, a range object is returned. The range object is an iterable of values—but the values are only generated as they’re actually needed. You can use the <a href="https://blog.finxter.com/what-is-asterisk-in-python/" title="What is the Asterisk / Star Operator (*) in Python?" target="_blank" rel="noreferrer noopener">asterisk operator</a> to unpack all values into the <a href="https://blog.finxter.com/the-separator-and-end-arguments-of-the-python-print-function/" title="Python Print Function [And Its SECRET Separator &amp; End Arguments]" target="_blank" rel="noreferrer noopener">print function</a> with <code>print(*range(10))</code>. Python waits as long as possible to generate the values of the iterable. </p>
<h2>Syntax Range Function</h2>
<p>You can use the <code>range()</code> function with three different argument lists: (i) with the <code>stop</code> argument only, (ii) with the <code>start</code> and <code>stop</code> arguments, or (iii) with the <code>start</code>, <code>stop</code>, and <code>step</code> arguments. </p>
<pre class="wp-block-preformatted"><strong>Syntax: </strong>
<strong><code>range(stop)</code></strong>
<code>range(start, stop)</code>
<code>range(start, stop, step)</code></pre>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><strong>Arguments</strong></td>
<td><code>start</code></td>
<td>An integer defining the first element of the <code>range</code> iterable</td>
</tr>
<tr>
<td></td>
<td><code>stop</code></td>
<td>An integer defining the last element. However, this element is not included in the r<code>ange</code> iterable. </td>
</tr>
<tr>
<td></td>
<td><code>step</code></td>
<td>An integer defining the difference between two subsequent elements in the <code>range</code> iterable. </td>
</tr>
<tr>
<td><strong>Return Value</strong></td>
<td><code>range</code></td>
<td>Returns an iterable range object that allows you to iterate over all values from <code>start</code> to <code>step</code> using the <code>step</code> size. </td>
</tr>
</tbody>
</table>
</figure>
<p class="has-black-color has-pale-pink-background-color has-text-color has-background"><strong>Interesting fact: </strong>the <code>range()</code> “function” is technically not a normal function but a constructor method of the <a href="https://docs.python.org/3/library/stdtypes.html#range" target="_blank" rel="noreferrer noopener" title="https://docs.python.org/3/library/stdtypes.html#range"><code>range</code> class</a>. Thus, it creates a new range object. </p>
<h2>How Math Genius Gauss Hacked His Teacher’s Exercise With the Range Function</h2>
<p>Do you know the following story of the <strong>brilliant mathematician Carl Friedrich Gauss</strong>? When 8-year old Gauss went to school, his math teacher sought a few minutes of breathing pause. He told his class to solve the problem of adding all subsequent numbers from 1-100: <code>1+2+3+...+100</code>.</p>
<p>But as little Gauss promptly reported the solution, the short pause was over before it began.</p>
<p>Surprised (and a bit grumpy as the story goes), the teacher asked the boy how he had come up with a solution so quickly. Gauss explained his simple solution. He organized the sequence into pairs of numbers each summing up to 101: <code>1+100,2+99,3+98,...,50+51</code>. There are 50 such pairs, so the total result was <code>50*101=5050</code>.</p>
<p>Yet, the modern-time little Gauss would be even lazier. He would type the following <a href="https://blog.finxter.com/python-one-line-x/" target="_blank" rel="noreferrer noopener" title="Python One Line X">one-liner </a>into his mobile Python app: <code>sum(range(1,101))</code>.</p>
<p>The <code>range()</code> function returns a sequence starting from the first value (inclusive) and ending in the second value (exclusive). The <a href="https://blog.finxter.com/python-one-line-sum-list/" target="_blank" rel="noreferrer noopener" title="Python One Line Sum List">sum function</a> sums up the values of this sequence. Combining both functions sums up the sequence from 1-100—faster than the brilliant Carl Friedrich Gauss.</p>
<hr class="wp-block-separator"/>
<h2>Python range() With One Argument Stop</h2>
<p>You can use the <code>range()</code> function with one argument <code>stop</code>. In this case, the range object goes from <code>start=0</code> to the <code>stop</code> argument (excluded) by using the default step size of one.</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2020/12/range_1-1-1024x576.jpg" alt="Python range() With One Argument Stop" class="wp-image-18336" srcset="https://blog.finxter.com/wp-content/uploads/2020/12/range_1-1-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<p>Here’s the example:</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="">for i in range(5): print(i)</pre>
<p>The output is:</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="">0
1
2
3
4</pre>
<h2>Python range() With Two Arguments Start + Stop</h2>
<p>You can use the <code>range()</code> function with two arguments <code>start</code> and <code>stop</code>. In this case, the range object goes from <code>start</code> to the <code>stop</code> integer value (excluded) by using the default step size of one.</p>
<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2020/12/range2-1024x576.jpg" alt="Python range() With Two Arguments Start + Stop" class="wp-image-18338" srcset="https://blog.finxter.com/wp-content/uploads/2020/12/range2-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p>Here’s the example:</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="">for i in range(1, 5): print(i)</pre>
<p>The output is:</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="">1
2
3
4</pre>
<h2>Python range() With Three Arguments Start + Stop + Step</h2>
<p>You can use the <code>range()</code> function with three arguments <code>start</code>, <code>stop</code>, and <code>step</code>. In this case, the <code>range</code> object goes from <code>start</code> to the <code>stop</code> integer value (excluded) by using the default step size of <code>step</code>.</p>
<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2020/12/range3-1024x576.jpg" alt="Python range() With Three Arguments Start + Stop + Step" class="wp-image-18339" srcset="https://blog.finxter.com/wp-content/uploads/2020/12/range3-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p>Here’s the example:</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="">for i in range(1, 5, 2): print(i)</pre>
<p>The output is:</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="">1
3</pre>
</p>
<h2>Interactive Shell Exercise About The Range Function</h2>
<p>The following code snippet matches men with women—the idea is to match the i-th man with the i-th woman, assuming that both lists have the same size. How to change the code to accomplish this task? </p>
<p> <iframe src="https://trinket.io/embed/python/5ab4ae4f21" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Replace the <code>XXXX</code> placeholder in the code to match the i-th man with the i-th woman!</em></p>
<p>You’ll find the solution… after the advertisement! <img src="https://s.w.org/images/core/emoji/13.0.1/72x72/1f642.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<hr class="wp-block-separator"/>
<p><strong>But before we move on, I’m excited to present you my brand-new Python book <a rel="noreferrer noopener" href="https://amzn.to/2WAYeJE" target="_blank" title="https://amzn.to/2WAYeJE">Python One-Liners</a></strong> (Amazon Link).</p>
<p>If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it’s also an <strong>introduction to computer science</strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!</em></strong></p>
<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="215" height="283" src="https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png" alt="" class="wp-image-5969"/></a></figure>
</div>
<p>The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). </p>
<p>Link: <a href="https://nostarch.com/pythononeliners" target="_blank" rel="noreferrer noopener">https://nostarch.com/pythononeliners</a></p>
<hr class="wp-block-separator"/>
<p><strong>Solution</strong>: The following code solves the exercise.</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="">men = ['Bob', 'Carl', 'Frank']
women = ['Ann', 'Alice', 'Liz'] for i in range(len(men)): print(men[i] + ' dances with ' + women[i])</pre>
<p>The idea is to use the <code><a href="https://blog.finxter.com/python-list-length-whats-the-runtime-complexity-of-len/" title="Python List Length – What’s the Runtime Complexity of len()?" target="_blank" rel="noreferrer noopener">len()</a></code> function to determine the <code>stop</code> argument automatically with <code>range(len(men))</code>. Note that <code>range(len(women))</code>, <code>range(3)</code>, and <code>range(0, 3)</code>, and <code>range(0, 3, 1)</code> would all solve the problem equally well.</p>
<h2>Python range() With Negative Step Size</h2>
<p>You can also use the range() function with negative step size. The meaning is “move from right to the left using the negative step size as the difference between two subsequent values. In this case, the start argument should be larger than the stop argument. </p>
</p>
<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2020/12/range4_neg-1024x576.jpg" alt="Python Range With Negative Step Size" class="wp-image-18349" srcset="https://blog.finxter.com/wp-content/uploads/2020/12/range4_neg-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p>Here’s an example:</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="">for i in range(4,0,-2): print(i)</pre>
<p>The output is:</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="">4
2</pre>
<p>Note that the <code>stop</code> argument is still not included in the <code>range</code> object.</p>
<h2>Range Puzzle</h2>
<p>Puzzles are a great and effective way to improve your Python skills. Can you solve this range puzzle?</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=""># Python Puzzle
print(sum(range(0,7)))</pre>
<h4>What is the output of this code snippet?</h4>
<p>You can check whether you solved this puzzle correctly, and determine whether you’re a master coder on our Puzzle app Finxter.com:</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://app.finxter.com/learn/computer/science/93" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="1024" height="526" src="https://blog.finxter.com/wp-content/uploads/2020/12/image-21-1024x526.png" alt="Range Puzzle" class="wp-image-18331" srcset="https://blog.finxter.com/wp-content/uploads/2020/12/image-21-1024x526.png 1024w, https://blog.finxter.com/wp-content/uplo...00x154.png 300w, https://blog.finxter.com/wp-content/uplo...68x394.png 768w, https://blog.finxter.com/wp-content/uplo...150x77.png 150w, https://blog.finxter.com/wp-content/uplo...age-21.png 1249w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>
</div>
<p>Are you a master coder?<br /><a href="https://app.finxter.com/learn/computer/science/93" target="_blank" rel="noreferrer noopener">Test your skills now!</a></p>
<h2>Summary</h2>
<p>The Python <code>range()</code> function creates an iterable of subsequent integers within a given range of values. </p>
<p>You can pass either only a <code>stop</code> argument in which case the <code>range</code> object will include all integers from <code>0</code> to <code>stop</code> (excluded). For example, <code>range(3)</code> results in <code>0, 1, 2</code>:</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="">for i in range(3): print(i) '''
OUTPUT:
0
1
2 '''</pre>
<p>As an alternative, you can pass <code>start</code>, <code>stop</code>, and <code>step</code> arguments in which case the range object will go from <code>start</code> to <code>step</code> using the given <code>step</code> size. For example, <code>range(2, 7, 2)</code> results in <code>2, 4, 6</code>:</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="">for i in range(2, 7, 2): print(i) '''
OUTPUT:
2
4
6 '''
</pre>
<p>I hope you enjoyed the article! To improve your Python education, you may want to join the popular free <a href="https://blog.finxter.com/email-academy/" target="_blank" rel="noreferrer noopener" title="Email Academy">Finxter Email Academy</a>:</p>
<hr class="wp-block-separator"/>
<p>Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!</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>
</p>
</p>
<p>The post <a href="https://blog.finxter.com/python-range-function/" target="_blank" rel="noopener noreferrer">Python range() Function — A Helpful Illustrated Guide</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/12/...ted-guide/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016