How to Use Python's xrange and range
Published on Aug. 22, 2023, 12:16 p.m.
The range()
function is used to generate a sequence of numbers. It takes three arguments: start
, stop
, and step
, and returns a sequence of numbers starting from start
, up to but not including stop
, in increments of step
. Here are some examples:
To generate a sequence of numbers from 0
to 9
:
for i in range(10):
print(i)
This will print the numbers 0
through 9
.
To generate a sequence of even numbers from 0
to 8
:
for i in range(0, 10, 2):
print(i)
This will print the even numbers 0
, 2
, 4
, 6
, and 8
.
You can also convert the range()
object into a list or tuple using the list()
or tuple()
constructor respectively.
In Python 2.x there is a similar function called xrange()
that returns an object that generates the numbers on-the-fly instead of generating a full list at once, making it memory efficient for large ranges. However, it is not available in Python 3.x as the built-in range()
function accomplishes the same.