# What does xrange() function do in Python?

python range
xrange
python

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.

## Syntax

The general syntax for defining the xrange is:

xrange(start,end,step)


This defines a range of numbers from start(inclusive) to end(exclusive).

## Xrange function parameters

The range function can take three parameters:

• Start: Specify the starting position of the sequence of numbers.
• End: Specify the ending position of the sequence of numbers
• Step: The difference between each number in the sequence.

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. ## Code and case examples

The following code explains how to define an xrange in Python:

### Case 1: When the end is defined

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)

### Case 2: When the start and end are defined

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)

### Case 3: When the start, end, and step are defined

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 COURSES
Related Courses
Related Courses