How to Use the Python xrange() Function

09/18/2021

Contents

In this article, you will learn how to use the Python xrange() function.

Python xrange() Function

The xrange() function in Python is a generator function that returns a sequence of integers. It is similar to the range() function, but it generates the sequence on-the-fly instead of creating a list of all the integers in memory. This can be useful for iterating over large ranges, or when memory usage is a concern.

The syntax for xrange() is similar to range(), but it only takes three arguments: start, stop, and step. Here is an example:

for i in xrange(1, 10, 2):
    print(i)

This will print the odd numbers from 1 to 9: 1, 3, 5, 7, 9.

Notice that xrange() does not include the stop value in the sequence, so the range above stops at 9, not 10.

You can also use xrange() in a loop to iterate over a range of values:

for i in xrange(10):
    print(i)

This will print the numbers from 0 to 9.

One thing to keep in mind is that xrange() is only available in Python 2. In Python 3, the range() function behaves like xrange() and generates the sequence on-the-fly, so you don’t need to use xrange() in Python 3.