Python xrange() function

Filed Under: Python
Python Xrange Function

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:

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

>>> x = xrange(5)
>>> print(type(x))
<type 'xrange'>
>>> 
>>> for n in x:
...     print(n)
... 
0
1
2
3
4
>>> 

2. xrange() with start and end values

>>> x = xrange(3, 6)
>>> for n in x:
...     print(n)
... 
3
4
5
>>> 

3. xrange() with start, end, and step variables

>>> 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.

Comments

  1. Pankaj malik says:

    Very nice

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages