The xrange() Function


This tutorial is going to deep dive to the very core of the range() and xrange() functions.
Please notice - the xrange() function was removed in python 3.x. A more accurate explanation is that the xrange() python 2.x function was renamed as range() in python 3.x, and the range() function was removed. Lets deep dive!


Python 2.X range() Function

It is a very common need to iterate over a sequence of numbers. To do so, one can write the sequence himself. This solution becomes unpractical when the sequence becomes too long. Another solution is to use a for loop (to iterate) along with a while loop (to create the sequence). While it is a much better idea than writing the sequence, it is still not a good solution
This is why the range() function was invented! range() is a built-in python function that creates a list of numbers.

The syntax:
range(start, end, step)

  1. Start - (optional) an integer that indicates the start value. If not given the default is 0.
  2. End - an integer that indicates the end value.
  3. Step - (optional) the difference between two items in the list. If not given the default is 1.

Python 2.X xrange() Function

The xrange() function doesn't create a list. Instead, it creates a sequence object (xrange object) that evaluates lazily. Lazy evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed.

There are reasons to favour the xrange() function: xrange() doesn't create a list that takes up space in the memory of the computer. Actually, there is no logic in creating a list for the sole purpose of iterating over it and never use it again. The xrange() function is faster and more elegant.

The syntax:
xrange(start, end, step)

  1. Start - (optional) an integer that indicates the start value. If not given the default is 0.
  2. End - an integer that indicates the end value.
  3. Step - (optional) the difference between two items in the list. If not given the default is 1.

When to Favour the Use of range() over xrange()

It is better to use the range() function when you want to create an actual list. In other cases (like iterating over a known sequence of numbers) it is better to use the xrange() function.

Python 3.x range() Function

In Python 3.x there is no xrange() function. One can think that this function was removed. The truth is that the range() function was removed and the xrange() function was renamed as range(). Under the hood the python 2 xrange() is quite the same as Python 3 range(). The functions are also similar in terms of performance.

How to Create a List Using the range() Function

If you want the Python 2 behavior for range in Python 3, you can always convert the range object to a list:

Here is an example:

#range to list list(range(5))