Draw a comparison between the range() and xrange() in Python
In python, both
xrange() functions produces the integer numbers between given start value and stop value.
xrange() function is only available in Python 2, in Python 3 it has been removed but
range() function of python 3 works same as
xrange() of python 2.
so difference between
xrange() functions became relevant only while we are using python 2.
xrange() on the basis of functionality, return value, return type, performance & speed test and compatibility.
xrange() function generates integer numbers within given range i.e
range(1,5,1) will produce
1, 2, 3, 4 and
xrange (1, 5, 1) will also produce the same. So there is no such difference between them in terms of functionality.
2. Return Value
range() creates a list , i.e range returns a python range objects.
range(1,100,1) will generate a python range of 99 integers in a memory at once.
xrange() functions returns an
xrange object i.e xrange only stores the range arguments and generates the number on demand. It evaluates lazily instead of generating all numbers at once like range(). Number on demand means, it produces number one by one as for loop moves to the next number. In every iteration of for loop, it generates the next number and assigns it to the iterator variable of for loop.
3. Return Type
range() return type is range object.
xrange() return type is xrange object.
4. Performance and Speed Test
With the help of
timeit module to test speed conclusion is drawn that
xrange() is found to be faster than the
xrange is faster and also saves memory as we know,
xrange() doesn’t generate as static list at the runtime i.e it only keeps one number in memory at a time to consume less memory but
range() uses a considerable amount of memeory .
So, if dealing with the extensive number
xrange() is better else range.
range() is compatible with python 2 and 3.
xrange() is not compatible with python 3.