Python range() function

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

The range() function is used to generate a sequence of numbers over time. At its simplest, it accepts an integer and returns a range object (a type of iterable). In Python 2, the range()  returns a list which is not very efficient to handle large data.

The syntax of the range()  function is as follows:


start(optional) Starting point of the sequence. It defaults to 0.
stop(required) Endpoint of the sequence. This item will not be included in the sequence.
step(optional) Step size of the sequence. It defaults to 1.

Let’s now look at a couple of examples to understand how range() works:

Example 1:

When range() is called with a single argument it generates a sequence of numbers from 0 upto the argument specified (but not including it). That’s why the number 5 is not included in the sequence.

Example 2:

Here range() is called with two arguments, 5 and 10. As a result, it will generate a sequence of numbers from 5 up to 10 (but not including 10).

You can also specify negative numbers:

Example 3:

Here the range() function is called with a step argument of 3, so it will return every third element from 1 to 20 (off course not including 20).

You can also use the step argument to count backwards.

The range() function is commonly used with for loop to repeat an action certain number of times. For example, in the following listing, we use range() to execute the loop body 5 times.

This code is functionally equivalent to the following:

However, in the actual code, you should always use range() because it is concise, flexible and performs better.

Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

3 thoughts on “Python range() function

  1. Balanagarajan Murugan

    #This solution is working fine
    def myfunc(string):
    for x in string:
    if string.index(x)%2==0:
    x= x.lower()
    x= x.upper()
    return ”.join(mylist)

  2. Joe

    How did the python creators make it so that start is a default argument, but stop, which comes after, is not? You can’t rewrite the range function for this very reason.


Leave a Reply

Your email address will not be published. Required fields are marked *