Python list is one of the very important data structures. To generate the list or sequence of elements, Python version 2 has two inbuilt handy functions called range()
and xrange()
.
Whereas, xrange is deprecated from Python version 3.
Before going into the difference between range and xrange, let’s see what it is.
Table of Contents
The function range and xrange generated the series of numbers. It takes 3 arguments- start, stop and step.
All three arguments belong to the numeric data type of Python.
Syntax or range()
range(<start>,<stop>,<step>)
Syntax or xrange()
xrange(<start>,<stop>,<step>)
We can use these two built-in methods in the for-loop statement. Here is an example using range() and xrange() for iterating over the loop and printing values from 1 to 9 (9 inclusive).
for-loop using range()
for x in range(1, 10, 1): print x
for-loop using xrange()
for x in xrange(1, 10, 1): print x
For both codes, the output is the same.
Output:
1 2 3 4 5 6 7 8 9
Both work exactly the same functionally and gives the same output.
then…
Even though the range and xrange give the same output, each element is evaluated differently during each iteration.
Let’s figure it out…
range():
The range is an inbuilt function that generates the list. It creates a static list before running the iteration.
Let’s take an example of range(1, 10)
.
Note: We are only passing two parameters. By default, the step-parameter value is 1. So, while each iteration, the value is incremented by one.
It creates the list of size 9 having elements 1 to 9 (9 inclusive) and returns the list object.
rObj = range(1, 10) print rObj #[1,2,3,4,5,6,7,8,9] type(rObj) #<type 'list'>
Related Read: 5 Major Difference Between List and Tuple in Python.
xrange():
Unlike range, xrange returns xrange sequence object.
xObj = xrange(1, 10) print xObj #xrange(1, 10) print type(xObj) #<type, 'xrange'>
It doesn’t create a list and each sequence element is evaluated lazily during each iteration. In other words, next iteration is similar to the returning last_value+1.
Taking an example of xrange(1, 10)
…
It evaluates each element in the sequence and returns values from 1 to 9 (9 inclusive).
The xrange() is another generator and the value is created using a special technique called as yielding. For more detail, you can read the generator function and yield value in Python.
As range() created a list of all the elements and save it before iterating. Whereas, xrange does not saves any element and evaluate each element during each iteration.
So, range() takes more memory to save these elements in the list.
Below is a code sample for testing. Generate the gigantic number of elements using both range and xrange. The range() will throw the MemoryError exception.
>>> xrange(int(1e15)) xrange(1000000000000000) >>> >>> >>> range(int(1e15)) Traceback (most recent call last): File "", line 1, in MemoryError >>>
It is clear if you have limited memory space to run your program where you need to generate a gigantic range of elements, you should use xrange() over the range().
Running xrange() is slower as compared to the range() as xrange evaluates the value of the element during each iteration. It is also called as lazy evaluation.
You can use timeit module to figure out the time required for each iteration during evaluating values for range() and xrange().
$ python -m timeit 'for i in range(1,1000000):' ' pass' 10 loops, best of 3: 28.2 msec per loop $ python -m timeit 'for i in xrange(1,1000000):' ' pass' 100 loops, best of 3: 9.87 msec per loop
If you observe, the time required to generate an element using xrange is higher than using the range. The range()
is faster than xrange()
.
Which one to use when?
If you are performing an action on a very large range of elements, it is good to use xrange(). It doesn’t save any elements. It just evaluates the next value whenever needed.
The xrange()
is very well optimized than range()
.
If you need faster execution of your program, use range().
In Python 2.x, the xrange() requires very little memory as it doesn’t save any sequence values. Even though xrange takes more time for iteration, the performance impact is very negligible.
So, they wanted to use xrange() by deprecating range(). In Python 3.x, they removed range (from Python 2.x) and renamed xrange() as a range().
Quick Summary:
Using a range with different Python Version…
To make the code portable so that it should work with both Python versions, use range()
instead of xrange()
.
Example 1: Printing all the values in the range from 0 to 9.
Using range():
for i in range(10): print(i)
Using xrange():
for i in xrange(10): print(i)
Output:
0 1 2 3 4 5 6 7 8 9
In the above example, we are only passing a single parameter (stop) to the functions range()
and xrange()
. The default value for parameters – start and step are zero and one respectively.
Example 2: Print all the odd numbers between 1 and 10.
Using range():
for i in range(1, 10, 2): print(i)
Using xrange():
for i in xrange(1, 10, 2): print(i)
Output:
1 3 5 7 9
It also works with negative values.
Example 3: Python program to print values from -1 to -9 using range and xrange.
Using range():
for i in range(-1, -10, -1): print(i)
Using xrange():
for i in xrange(-1, -10, -1): print(i)
Output:
-1 -2 -3 -4 -5 -6 -7 -8 -9
If you are new to this portal, we have a complete Python tutorial available for FREE. Let’s start learning Python.
This is all about the difference between range and xrange in Python. Hope it clears your doubt so that you are able to make the decision which one to use. If you have any queries, feel free to write in the comment.
You should consider taking this down, as it really isn’t current and leads the reader through a bunch of stuff, that in the end, reads the Python3 disclaimer. If you feel it is still relevant information then inform the reader this is for 2.X in the beginning and not waste their time. All that said, it is a good presentation.
Thanks, Ted!
Considering reader’s perspective it is really a good suggestion.
I have updated the post and mentioned as xrange is deprecated from Python 3 at the beginning.
Hope this helps.
Happy Pythoning!