Difference between range() and xrange() in Python

Because of the fact that xrange() evaluates only the generator object containing only the values that are required by lazy evaluation, therefore is faster in implementation than range().

Important Points: 

  • If you want to write code that will run on both Python 2 and Python 3, use range() as the xrange function is deprecated in Python 3.
  • range() is faster if iterating over the same sequence multiple times.
  • xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory, however)

range()

xrange()

Returns a list of integers. Returns a generator object.
Execution speed is slower Execution speed is faster.
Takes more memory as it keeps the entire list of elements in memory. Takes less memory as it keeps only one element at a time in memory.
All arithmetic operations can be performed as it returns a list. Such operations cannot be performed on xrange().
In python 3, xrange() is not supported. In python 2, xrange() is used to iterate in for loops.


range() vs xrange() in Python

The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range(). Both are implemented in different ways and have different characteristics associated with them. The points of comparison are:

  • Return Type
  • Memory
  • Operation Usage
  • Speed

Similar Reads

Python range() function

The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequences on a sequence of numbers using Python loops....

Python xrange() function

The xrange() function in Python is used to generate a sequence of numbers, similar to the Python range() function. The Python xrange() is used only in Python 2.x whereas the range() function in Python is used in Python 3.x....

Difference between range() and xrange() in Python

...