Python xrange() function is used to generate a sequence of integers. This function is part of Python 2. In Python 3, the name has been changed to range() function.
Python xrange() Syntax
The xrange() function syntax is:
1 |
xrange(start, end, step) |
- The
start
variable defines the starting number, it’s included in the output sequence of integers. It’s optional and the default value is 0. - The
end
variable defines the ending number, it’s excluded in the output sequence of integers. It’s a mandatory parameter. - The
step
defines the difference between each number in the sequence. It’s optional with the default value is 1. - When only one argument is passed, it’s treated as the
end
variable.
Python xrange() function examples
Let’s look at some examples of using xrange() function using Python Interpreter.
1. xrange() with only end variable
1 2 3 4 5 6 7 8 9 10 11 12 |
>>> x = xrange(5) >>> print(type(x)) <type 'xrange'> >>> >>> for n in x: ... print(n) ... 1 2 3 4 >>> |
2. xrange() with start and end values
1 2 3 4 5 6 7 8 |
>>> x = xrange(3, 6) >>> for n in x: ... print(n) ... 3 4 5 >>> |
3. xrange() with start, end, and step variables
1 2 3 4 5 6 7 8 9 |
>>> x = xrange(3, 10, 2) >>> for n in x: ... print(n) ... 3 5 7 9 >>> |
Python range() vs xrange() functions
If you are using Python 2.x version, use the xrange() function to generate a sequence of numbers. If you are on Python 3, then use the range() function since xrange() has been renamed to range() function.