The xrange()
function in Python is used to generate a sequence of numbers, similar to the range()
function. However, xrange()
is used only in Python 2.x whereas range()
is used in Python 3.x.
The general syntax for defining the xrange is:
xrange(start,end,step)
This defines a range of numbers from start(inclusive) to end(exclusive).
The range function can take three parameters:
It is must to define the end position. However, the start and step are optional. By default, the value of start is 0 and for step it is set to 1.
The xrange()
function creates a generator-like object that can be used in a for
loop to iterate over a range of numbers, similar to the range()
function in Python 3.
The following code explains how to define an xrange()
in Python:
end
is definedend=5x = xrange(end) #create a sequence of numbers from 0 to 4print(x)for n in x:print(n)
end
of the range is defined as 5.x
is pointing to the object created by the xrange
function in line 4.for
loop is printing the sequence of values in the object.start
and end
are definedstart=2end=5y = xrange(start,end) #create a sequence of numbers from 2 to 5print(y)for n1 in y:print(n1)
start
of the range is defined as 2
and the end
is defined as 5
.y
is pointing to the object created by the xrange
function in line 6.for
loop is printing the sequence of values in the object.start
, end
, and step
are definedstart=2end=5step=2z = xrange(start,end,step) #create a sequence of numbers from 3 to 10 with increment of 2print(z)for n2 in z:print(n2)
start
of the range is defined as 2
, the end
is defined as 5
and step
is defined as 2.z
is pointing to the object created by the xrange function in line 6.for
loop is printing the sequence of values in the object.The xrange
function generates numbers up to, but not including, the end parameter. So in our output, xrange(2, 6, 2) generates the numbers 2, 4, which are the numbers greater than or equal to 2, but less than 6, that are divisible by 2.
Free Resources