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 Python 3, there is no xrange, but the range function behaves like xrange in Python 2. If you want to write code that will run on both Python 2 and Python 3, you should use range().
- range() – This returns a range object (a type of iterable).
- xrange() – This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called “lazy evaluation“.
Both are implemented in different ways and have different characteristics associated with them. The points of comparison are:
- Return Type
- Operation Usage
range() returns – range object.
xrange() returns – xrange() object.
The return type of range() is : <type 'list'> The return type of xrange() is : <type 'xrange'>
The variable storing the range created by range() takes more memory as compared to the variable storing the range using xrange(). The basic reason for this is the return type of range() is list and xrange() is xrange() object.
The size allotted using range() is : 80064 The size allotted using xrange() is : 40
As range() returns the list, all the operations that can be applied on the list can be used on it. On the other hand, as xrange() returns the xrange object, operations associated to list cannot be applied on them, hence a disadvantage.
Traceback (most recent call last): File "1f2d94c59aea6aed795b05a19e44474d.py", line 18, in print (x[2:5]) TypeError: sequence index must be integer, not 'slice'
The list after slicing using range is : [3, 4, 5] The list after slicing using xrange is :
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().
- 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)
|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.|