Difference Between range and xrange in Python | xrange vs range

Difference Between range and xrange in Python | xrange vs range

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.

What is range() and xrange()?

The function range and xrange generated the series of numbers. It takes 3 arguments- start, stop and step.

  • Start is the first integer value generated in the range. It is optional parameter and default value is 0.
  • Stop is the last integer value where you would like to stop iterating. It is required parameter.
  • Step is integer value by which each element is incremented. It is optional parameter and default value is 1.

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…

What is the difference between range and xrange?

Even though the range and xrange give the same output, each element is evaluated differently during each iteration.

Let’s figure it out…

  • How are they different from each other?
  • Which one does take more memory?
  • Which one is faster to execute (performance)?
  • Why is xrange deprecated from Python 3.x?

xrange vs range | Working Functionality:

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.

Which does take more memory?

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().

Which is faster?

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().

Deprecation of xrange() for Python 3.x

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…

  • In Python 3.x, xrange() is removed and there is an only range()
  • range() in Python 3.x works exactly same as xrange() in Python 2.x

To make the code portable so that it should work with both Python versions, use range() instead of xrange().

range() and xrange() Examples

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.

2 Comments

  1. 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.

    1. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *