This comprehensive Linux guide expects that you run the following commands as root user but if you decide to run the commands as a different user then ensure that the user has sudo access and that you precede each of the privileged commands with sudo

The range() and xrange() functions in python programming are used to generate integers or whole numbers in a given range(starting and ending point). The two functions provide the same output but there is a little difference in them. We will discuss the difference with examples.

Note: In python 3.x, the range() function has been decommissioned and the xrang() function is available as range(). So, there is only one function to generate range of numbers in Python 3.x.

Difference between range() and xrange()

There are several different traits in both the functions. We will discuss the different types of properties separately.

Following are the different properties of these two funtions:

  • Functional/Operational Difference
  • Return Values/type
  • Memory Usage
  • Speed

Functional/Operational Difference

Most of the times, the xrange() works same as the range() function. Both of the functions produce a list of numbers for us to use in our program.

So, in terms of functionality or operation, both of the functions work the same way.

Return Values/Types

The primary difference between these two functions is the return type.

  • range() returns a list of numbers

Example:

a = range(1,999) 
print ("The return type of range() is : ") 
print (type(a)) 

OUTPUT:
The return type of range() is : 
<type 'list'>

  • xrange() returns an xrange() object

Example:

a = xrange(1,999) 
print ("The return type of range() is : ") 
print (type(a)) 

OUTPUT:
The return type of range() is : 
<type 'xrange'>

Memory Usage

 There is a big difference in the memory usage of both the functions.

The xrange() is more memory efficient than the range() function and uses less memory. The basic reason for this is the return type of range() is list and xrange() is xrange() object.

r = range(10000)
print(sys.getsizeof(r))  
 
x = xrange(10000)
print(sys.getsizeof(x))

OUTPUT:
80072
40

Speed

The of the memory saving is that looking up indexes in xrange() will take slightly longer.

Following code can be used to show that the xrange() function is 10% slower:

from __future__ import print_function
import timeit
 
r = range(10000)
x = xrange(10000)
 
def range_index():
    z = r[9999]
 
def range_xindex():
    z = x[9999]
 
if __name__ == '__main__':
    import timeit
    print(timeit.timeit("range_index()", setup="from __main__ import range_index",   number=10000000))
    print(timeit.timeit("range_xindex()", setup="from __main__ import range_xindex", number=10000000))


OUTPUT:
2.16770005226
2.35304307938

This output shows that xrange() is 10% slower than range()

Tip: If you want to write code that will run on both Python 2 and Python 3, use range() as the xrange() function is decommissioned in Python 3