What does xrange() function do in 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 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.

svg viewer

Code and case examples

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

Case 1: end is defined

end=5
x = xrange(end) #create a sequence of numbers from 0 to 4
print(x)
for n in x:
print(n)

Explanation

  • Line 1: Here, the end of the range is defined as 5.
  • Lines 2-3: The var x is pointing to the object created by the xrange function in line 4.
  • Lines 4-5: And then the for loop is printing the sequence of values in the object.

Case 2: start and end are defined

start=2
end=5
y = xrange(start,end) #create a sequence of numbers from 2 to 5
print(y)
for n1 in y:
print(n1)

Explanation

  • Lines 1-2: Here, the start of the range is defined as 2 and the end is defined as 5.
  • Lines 3-4: The var y is pointing to the object created by the xrange function in line 6.
  • Lines 5-6: And then the for loop is printing the sequence of values in the object.

Case 3: start, end, and step are defined

start=2
end=5
step=2
z = xrange(start,end,step) #create a sequence of numbers from 3 to 10 with increment of 2
print(z)
for n2 in z:
print(n2)

Explanation

  • Lines 1-3: Here, the start of the range is defined as 2, the end is defined as 5 and step is defined as 2.
  • Lines 4-5: The var z is pointing to the object created by the xrange function in line 6.
  • Lines 6-7: And then the for loop is printing the sequence of values in the object.

Output

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.

Copyright ©2024 Educative, Inc. All rights reserved