Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»python»The Python range Function Guide
    python

    The Python range Function Guide

    March 23, 2023No Comments15 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    The built-in range function of Python comes in help if there is a requirement to carry out a certain activity a predetermined number of times. Because of your extensive familiarity with Python, I’m sure you’ve worked with it previously. However, what effect does it have? When you’ve finished reading this guide, you’ll be able to:

    • Understand how the Python

      range

      function works
    • Know how the implementations differ in Python 2 and Python 3
    • Have seen a number of hands-on

      range()

      examples
    • Be equipped to work around some of its limitations

    Let’s get

    cracking!

    The History of Python’s

    Even though the range() function in Python 2 and the range() function in Python 3 have the same name, they are not even remotely similar. In point of fact, the function known as xrange in Python 2 has been rechristened as range() in Python 3, and both names refer to the same thing.

    In the beginning, range() and xrange() both created numbers that could be iterated over using for-loops. However, range() generated a list of those numbers all at once, but xrange() produced numbers lazily, which means that numbers were returned one at a time as they were required.

    Because keeping large lists around uses up memory, it shouldn’t come as a surprise that xrange() has replaced range() with its name and all of its arguments. PEP 3100 has additional information regarding this decision as well as the history behind the debate between xrange() and range(). Please take note that PEP is an abbreviation for Python Enhancement Proposal. PEPs are documents that can cover a wide variety of subjects, such as suggested new features, governance, and philosophy. Other topics that can be covered include style.

    There are an overwhelming number of them. PEP 1 is a fantastic place to begin because it provides an explanation of how they operate.

    The remainder of this article will walk you through using the method in its current iteration in Python 3.

    Here we

    go!

    Let’s Loop

    First things first: let’s have a look at how looping works, and then we’ll go on to examining how range() operates. The process of looping is an important idea in computer science. Learning how to use loops effectively is one of the first things you need to do if you want to have a successful career as a programmer.

    The following is an illustration of a for-loop in

    Python:

    captains = ['Janeway', 'Picard', 'Sisko']
    for captain in captains:
        print(captain)
    

    The output looks like

    this:

    Janeway
    Picard
    Sisko
    

    As you can see, a for-loop gives you the ability to repeat the execution of a certain section of code an unlimited number of times. In this instance, we printed each of the captains’ names by looping through a list of those who serve as captains.

    Even if Star Trek is awesome and everything, you probably want to do something more interesting than just run through a list of captains. There are situations in which all you need to do is run a section of code a predetermined number of times. You can accomplish that with the help of loops!

    Experiment with the following code using numbers that are divisible by

    three:

    numbers_divisible_by_three = [3, 6, 9, 12, 15]
    for num in numbers_divisible_by_three:
        quotient = num / 3
        print(f"{num} divided by 3 is {int(quotient)}.")
    

    This is how the output of that loop will seem.

    this:

    3 divided by 3 is 1.
    6 divided by 3 is 2.
    9 divided by 3 is 3.
    12 divided by 3 is 4.
    15 divided by 3 is 5.
    

    This is the output that we intended, so the loop did an adequate job of doing the task; but, there is another way to accomplish the same thing, and that is by using the range() function. Please take note that the preceding code example used some string formatting. Check out Python String Formatting Best Practices and Python 3’s f-Strings: An Improved String Formatting Syntax (Guide) if you want to learn more about this subject. Both of these resources are available online.

    Allow me to show you how the range() function can help you simplify your code now that you have a better understanding of loops.

    life.

    Python

    So how exactly does the range function in Python work? To put it another way, the range() function enables you to construct a sequence of numbers that fall within a specified range. You have the ability to determine where that series of numbers will begin and stop, as well as the magnitude of the gap that will exist between each number in the series, based on the amount of parameters that you send to the function.

    Here’s a look behind the scenes at range() in

    action:

    for i in range(3, 16, 3):
        quotient = i / 3
        print(f"{i} divided by 3 is {int(quotient)}.")
    

    You were able to easily generate a range of numbers that are divisible by 3 using this for-loop, which freed you from the responsibility of providing each of the individual numbers on your own. Note: Although this example demonstrates the correct way to use range(), it is often frowned upon to use range() excessively in for-loops. However, this example demonstrates the correct way to use range().

    The following application of the range() function, for instance, is typically regarded as not

    Pythonic:

    captains = ['Janeway', 'Picard', 'Sisko']
    for i in range(len(captains)):
        print(captains[i])
    

    range() is fantastic for use in the creation of.

    iterables of numbers, but when you really need to, it’s not the greatest option.

    iterate over the information that may be looped over using the

    in the role of the operator.

    Check out if you are interested in learning more.

    How to Make Your Loops in Python Be More Like Python.

    There are three different approaches to determine range.()

    :


    1. range(stop)

      takes one argument.

    2. range(start, stop)

      takes two arguments.

    3. range(start, stop, step)

      takes three arguments.

    When you call range() with one argument, you will obtain a series of numbers that starts at 0 and includes every whole number up to, but does not include, the number you have specified as the stop. These numbers will be returned to you in the order in which they were passed to range().

    The following is how it appears in the

    practice:

    for i in range(3):
        print(i)
    

    This will be what the output of your loop looks like.

    this:

    0
    1
    2
    

    That checks out: we have all the full numbers ranging from 0 all the way up to but not including 3, which you gave as the stop number.

    .

    When you call range() with two arguments, not only do you get to determine where the series of numbers stops, but you also get to decide where it starts. This means that you are not required to always begin at 0 in the series of numbers. It is possible to construct a sequence of numbers using the range() function.

    A to

    B by employing a range that spans A and B. Let’s find out how to create a range beginning with 1 in the next step.

    Try invoking range() with the number two.

    arguments:

    for i in range(1, 8):
        print(i)
    

    Your output will look like

    this:

    1
    2
    3
    4
    5
    6
    7
    

    You have all of the whole numbers ranging from 1 (the number you specified as the starting point) all the way up to but not including 8 at this point. (the number you provided as the stop ).

    However, if you add one more argument, you will be able to recreate the output that you had previously when you were utilizing the list that was entitled numbers_divisible_by_three.

    .

    When you call range() with three arguments, you not only get to determine where the series of numbers will start and stop, but you also get to choose how large of a gap there will be between each successive number in the series. If you do not supply a step, range() will automatically behave as if the step is 1. If you do specify a step, range() will treat it as the default value.

    Note:

    step can be either a positive or a negative number, but it must always be a number and never 0.

    :


    >>>

    >>> range(1, 4, 0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: range() arg 3 must not be zero
    

    You will receive a message indicating that you have made a mistake if you attempt to use 0 as your step.

    You can finally go back and look at the loop that we covered before with division by 3 now that you understand how to utilize step.

    Give it a shot.

    yourself:

    for i in range(3, 16, 3):
        quotient = i / 3
        print(f"{i} divided by 3 is {int(quotient)}.")
    

    Your result will have the exact same format as the output of the for-loop that you observed earlier on in this piece, when you were working with the list that was labeled numbers_divisible_by_three.

    :

    3 divided by 3 is 1.
    6 divided by 3 is 2.
    9 divided by 3 is 3.
    12 divided by 3 is 4.
    15 divided by 3 is 5.
    

    As you can see from the above illustration, you can make use of the step argument to gradually go up to a greater number. That is referred to as

    incrementing.

    Incrementing With

    If you want to increment, then step must be a positive number. Incrementing requires a positive step value. Enter the following into your search engine to get an understanding of what this implies in practice:

    code:

    for i in range(3, 100, 25):
        print(i)
    

    The output of your loop will look like this if your step size is 25, for example:

    this:

    3
    28
    53
    78
    

    You were given a set of numbers that were all greater than the one before it by a factor of 25, which was the step that you specified.

    It is time to look at how you can step backwards through a range now that you have seen how you can step forwards through a range.

    backwards.

    Decrementing With

    If the value of your step is positive, it means that you are moving through a sequence of increasing numbers, which indicates that you are incrementing. If your step is negative, then you are moving through a succession of lowering numbers and decrementing. If your step is positive, then you are incrementing. This enables you to travel through the numbers in the opposite direction.

    Your step should be minus two in the following illustration. This indicates that you will be subtracting 2 from each value in each case.

    loop:

    for i in range(10, -6, -2):
        print(i)
    

    Your decrementing loop will provide output that looks like this.

    this:

    10
    8
    6
    4
    2
    0
    -2
    -4
    

    You were given a set of integers that each fell inside a range in which they were lower than the previous number by a factor of 2, the absolute value of the step you provided.

    Using the range(start, stop, step) syntax to generate a range that decrements is the most Pythonic approach to get the job done. On the other hand, Python does include a reversed function that is built right in. If you enclose the range() function within the reversed() function, then you will be able to output the integers in the opposite order.

    Give it a try.

    try:

    for i in reversed(range(5)):
        print(i)
    

    You’ll get

    this:

    4
    3
    2
    1
    0
    

    It is possible to iterate over a sequence of numbers that is decrementing by using the range() function, although the reversed() function is typically used to loop over a sequence in the opposite way. Please take note that the reversed() function also works with strings. You can get more information about the capabilities of the reversed() method when used with strings in.

    How to Perform a String Inversion Using Python

    .

    Advanced Usage Examples for Python’s

    It is time to delve a little more into the use of range() now that you are familiar with its fundamentals.

    range() is most commonly employed for two purposes:

    purposes:

    1. Executing the body of a for-loop a specific number of times
    2. Creating more efficient iterables of integers than can be done using

      lists or tuples

    The first use is most likely the most typical one, and you could argue that itertools offers a more time- and resource-effective approach to the construction of iterables than range() provides.

    When it comes to using range, here are some additional considerations to bear in mind.

    The function range() is a type in.

    Python:


    >>>

    >>> type(range(3))
    <class 'range'>
    

    You can get to individual items in a range() by using an index, exactly like you would with a

    list:


    >>>

    >>> range(3)[1]
    1
    >>> range(3)[2]
    2
    

    Even slicing notation can be used on a range(), although the output in a REPL may look a little weird at first.

    first:


    >>>

    >>> range(6)[2:5]
    range(2, 5)
    

    When you slice a range(), all you get back is another range(), even though the result might look strange.

    The fact that members of a range() can be accessed by index and that range()s can be sliced draws attention to an essential aspect: range() is a lazy iterator, in contrast to a list, but it is not an iterator.

    .

    Floats and

    You might have realized by this point that every single number that we have discussed up to this point has been a whole number, which is also referred to as an integer. This is due to the fact that range() can only accept integer arguments.

    arguments.

    A Word on Floats

    In Python, an integer is considered to be of the type known as a float if it is not a whole number. There are a few key distinctions to keep in mind when comparing integers and floats.

    An integer (int data

    type):

    • Is a whole number
    • Does not include a decimal point
    • Can be positive, negative, or

      0

    A floating point number (float data

    type):

    • Can be any number that includes a decimal point
    • Can be positive or negative

    See what happens when you call range() with a float and try it out.

    happens:

    for i in range(3.3):
        print(i)
    

    The following error message should appear for you:

    message:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'float' object cannot be interpreted as an integer
    

    If you are looking for a workaround that would enable you to make use of floats, one option that you have is to utilize

    NumPy.

    Using

    NumPy is a Python library that was developed by a third party. If you are going to use NumPy, the first thing you need to do is check to see if it is already installed on your computer.

    This is how you can go about doing that in your own.

    REPL:


    >>>

    >>> import numpy
    

    If you see an error message that says ModuleNotFoundError, then you need to install the missing module. To accomplish this, open up the command line on your computer and type “pip install numpy.”

    When you have it installed, proceed to the next step.

    following:

    import numpy as np
    np.arange(0.3, 1.6, 0.3)
    

    It will come back.

    this:

    array([0.3, 0.6, 0.9, 1.2, 1.5])
    

    You can follow these instructions if you wish to print each number on a separate line.

    following:

    import numpy as np
    for i in np.arange(0.3, 1.6, 0.3):
        print(i)
    

    This is the case in

    output:

    0.3
    0.6
    0.8999999999999999
    1.2
    1.5
    

    What is the origin of the value 0.8999999999999999?

    When attempting to save decimal floating-point numbers in binary floating-point format, computers often have problems. This results in all kinds of strange representations of the numbers involved. Note: If you want to find out more about the reasons why there are problems displaying decimals, you can look at the following:

    this article, together with the other,

    Python documentation .

    You should probably have a peek at the as well.

    The decimal library is a bit of a step backward in terms of performance and readability, but it does give you the ability to express decimal values in a precise manner.

    There is also the possibility of utilizing the round() function, which details may be found in.

    How to Round Numbers in the Python Programming Language It is important to keep in mind that the round() function has its own peculiarities, which can lead to unexpected outcomes.

    Whether or whether these inaccuracies in floating point are a problem for you is entirely dependent on the issue that you are trying to solve. It’s possible that the inaccuracies will be in something as trivial as the sixteenth decimal place, but even if they are, they will still be present. Because they are so insignificant, you don’t need to bother about them unless you’re doing anything like calculating the orbital trajectories of satellites or something similar.

    You might also try using the np.linspace() function as an alternative. It effectively accomplishes the same goal but with a few tweaks to the parameters. You can specify start and finish (both inclusive) when using the np.linspace() function, in addition to the length of the array. (instead of step ).

    For example, np.linspace(1, 4, 20) returns 20 values that are equally spaced out, such as 1.0,…, 4.0. On the other hand, the results of the expression np.linspace(0, 0.5, 51) are 0.00, 0.01, 0.02, 0.03,…, 0.49, and 0.50. Take note: If you want to find out more, you can read.

    Look Mom, No For-Loops! Array Programming Using NumPy and this Convenient Tool

    a reference to NumPy

    .

    Go Forth and Loop

    You now have an understanding of range() and how to get around the constraints of the function. You are also familiar with the changes that have been made to this essential function in the transition from Python 2 to Python 3.

    The next time you need to carry out a certain task a predetermined number of times, you’ll be ready to loop until your heart’s content!

    Happy Pythoning!

    Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Language The Python range Function Guide
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleGzip module in Python
    Next Article args and kwargs in Python

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Coroutine in Python

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.