In Python programming, we have two range() and xrange() functions that generate the integer numbers from a given start and stop value. Here, we are discussing the main differences between Python xrange and range functions.
Python xrange() vs range()
The range() function has already replaced xrange(), but it is still good to learn the differences and similarities between these two. It is helpful when you get to work on a legacy project developed in Python 2 and using xrange().
What are Python range and xrange functions?
In Python 2, we had the two underlying methods to generate a list of integers within a given range.
- range()
- xrange()
However, in Python 3, range() was decommissioned, and xrange() was renamed to range().
Hence, in Python 3, we get a single function that could produce the numbers from a given range. It was none other than the Python range function.
The range() function in Python 3 is just a re-implementation of the xrange() of Python 2. It actually works the same way as the xrange does.
If you are using Python 2, then only the difference between xrange() and range() is meaningful to you.
The difference between Python xrange and range
The two range functions have many different traits. These could relate to performance, memory consumption, speed, and internal design. Each of these has its implementation differently. Now, let’s review each such differences one by one.
Operational difference
In most cases, both xrange and range operate precisely in the same way. They both give a way to produce a list of numbers for you to use.
Hence, we can say that both are similar in terms of functionality. Let’s see some examples now:
The expression range (1, 7, 2) will produce [1, 3, 5] and xrange(1, 7, 2) will produce [1, 3, 5]. Hence, you can conclude that they have a similar execution pattern and output.
Return values and type
It is the primary source of difference between Python xrange and range functions.
The range() returns a list-type object. For example, the expression range(1, 100, 1) will produce a 99 int numbers range. It gets all the numbers in one go.
>>> r = range(1, 100, 1) >>> type(r) <type 'list'> >>> len(r) 99
On the other hand, the xrange() provides results as an xrange object. It performs a lazy evaluation. It keeps the arguments and produces numbers on call. Unlike range(), it avoids getting all the numbers in one go.
The xrange object allows iteration, indexing, and the len() method. You can have a for loop to traverse it and get the numbers in every iteration.
>>> xr = xrange(1, 100, 1) >>> type(xr) <type 'xrange'> >>> xr[0] 1 >>> for it in xr: ... print(it) ... 1 2 3 ... 99
Also Check: Print Alphabet Pattern “A” Using Python Range()
Python xrange vs. range – compare the speed
We have got a timeit module in Python to capture the execution time of any function. We’ll use it in our test and see which of the xrange or range is faster.
Calculate the time of range()
We executed range() in our test three times, see the below example and the time it took for execution:
>>> import timeit >>> timeit.timeit('"-".join(str(num) for num in range(10000))', number=10000) 22.56510010000011 >>> timeit.timeit('"-".join(str(num) for num in range(10000))', number=10000) 22.796818399999893 >>> timeit.timeit('"-".join(str(num) for num in range(10000))', number=10000) 24.003325399999994
Again, we ran the same test with xrange() three times and recorded their execution time.
>>> timeit.timeit('"-".join(str(num) for num in xrange(10000))', number=10000) 20.672853799999984 >>> timeit.timeit('"-".join(str(num) for num in xrange(10000))', number=10000) 20.471903500000053 >>> timeit.timeit('"-".join(str(num) for num in xrange(10000))', number=10000) 20.15995029999999
From the above tests and results, you can assess that xrange is faster than the standard range function.
- While using xrange, you would have noticed that it doesn’t produce a static list as the range() function does. Instead, it is more like a generator that gives values on demand. This technique is popularly known as yielding.
- The range() function gets all the numbers at once before executing any instruction in the loop.
Here are some facts for your reference:
- The primary issue with the standard range() function is that it consumes a significant amount of memory, especially for a bigger range of numbers.
- xrange() function always provides the next element on demand. It means that only one item exists in memory at a time. Hence, it consumes less memory.
What to prefer xrange or range?
It’s a tradeoff between an instant result or a segmented output. With xrange, we get a speedier response; also, its consumption of memory is lower.
Hence, it is evident that Python xrange has an edge over the traditional range() function. Let’s now look at some cases to understand which of these methods fits where.
Where should we use xrange()?
- When the range has a broader scope, there we recommend using the xrange(). It will improve speed and require less memory.
- If you plan to run on smaller devices (which have memory constraints), then with xrange(), you may not see buffer issues.
- Since xrange() evaluates items with a slack, you may break them at any point when needed. In this way, you can avoid creating the entire list.
Where should we use range()?
- When you have to traverse the list frequently, then it’s better to use range(). With xrange(), it would be an overhead to instantiate an integer object for every indexing request.
- If you are not looking for a wide range, then using the range() function is the right idea.
- Since the range method returns a list object, you can utilize all of its functions. On the contrary, xrange provides a bare integer object which requires indexing.
- Interestingly, if you wish to keep your Python 2 code compatible with version 3, then you should prefer using the range method.
Python xrange vs. range compatibility
In Python 3, the xrange function doesn’t exist, whereas it provides the range() function. The reality is that “xrange” has got its name changed to “range” in Python 3.
So, if you step to call xrange() in Python 3, it will raise the below error.
NameError: name ‘xrange’ is not defined
Also, if you opt to import the xrange, even then the following error will occur.
ImportError: No module named ‘xrange’
Hence, you may decide to use range() instead of xrange() to maintain compatibility across different versions.