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.
Code and case examples
The following code explains how to define an xrange() in Python:
Case 1: end is defined
end=5x = xrange(end) #create a sequence of numbers from 0 to 4print(x)for n in x:print(n)
Explanation
- Line 1: Here, the
endof the range is defined as 5. - Lines 2-3: The var
xis pointing to the object created by thexrangefunction in line 4. - Lines 4-5: And then the
forloop is printing the sequence of values in the object.
Case 2: start and end are defined
start=2end=5y = xrange(start,end) #create a sequence of numbers from 2 to 5print(y)for n1 in y:print(n1)
Explanation
- Lines 1-2: Here, the
startof the range is defined as2and theendis defined as5. - Lines 3-4: The var
yis pointing to the object created by thexrangefunction in line 6. - Lines 5-6: And then the
forloop is printing the sequence of values in the object.
Case 3: start, end, and step are defined
start=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)
Explanation
- Lines 1-3: Here, the
startof the range is defined as2, theendis defined as5andstepis defined as 2. - Lines 4-5: The var
zis pointing to the object created by the xrange function in line 6. - Lines 6-7: And then the
forloop 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.
Free Resources