These two functions are used for iterating for a certain number of times in for loops. In Python 3 for data science, it does not contain xrange(). In Python 2 range() behaves similar to xrange().
- range() – It returns the list of numbers that are created using range() function.
- xrange() – Use for returning the generator object which is use for display of numbers by looping. A particular range is displayed only on demand, and so, it is known as “Lazy evaluation”.
Below we will be comparing both the range() and xrange() functions on some parameters.
The parameters are as follows:
- In the case of range() the return type is list.
- In case of xrange() an xrange() object is returned.
The range created by range() which is stored in a variable takes up much more memory than xrange(). This happens because the return type of range() is list and that o xrange() is object.
We have seen that range() returns a list so, whatever operation is possible on a list is possible in case of range(). But in the case of xrange() it is not possible as it returns xrange object.
xrange() is faster when compared to range() as it uses lazy evaluation which is already discussed at the beginning of this article.
- When writing codes that should run on both Python 3 and Python 2 range() is the only option.
- range() will be faster in case we are iterating on the same sequence multiple times.
- In terms of memory range() is the worst one can get.