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 values of start and step have been set to 0.
The following code explains how to define an xrange
in Python:
print("Specify end position only\n") end=5 print("end position:",end) x = xrange(end)#create a sequence of numbers from 0 to 4 print(x) for n in x:#print the elements using a for loop print(n)
print("\n\nSpecify both start and end position") start=2 end=5 print("start position:",start) print("end position:",end) y = xrange(start,end)#create a sequence of numbers from 2 to 5 print(y) for n1 in y:#print the elements using a for loop print(n1)
print("\n\nSpecify both start,end position and step") start=2 end=5 step=2 print("start position:",start) print("end position:",end) print("step:",step) z = xrange(3,10,2)#create a sequence of numbers from 3 to 10 with increment of 2 print(z) for n2 in z:#print the elements using a for loop print(n2)
RELATED TAGS
View all Courses