What is the difference between range and xrange in Python

Introduction

This question is frequently asked on many technical websites. Before we clarify the key difference between the two, please note that xrange is a Python 2.x function. In other words, Python 2.x has both range and xrange. On the other hand, in Python 3.x there is only one function called range. So this question is only relevant to Python 2.x. In Python 3.x, the range function behaves like xrange in Python 2.x

Functionality

range and xrange are two builtin functions to generate a sequence of numbers. In the following examples, the output will be the same whether we use range or xrange…

Differences

If both functions produce the same output, what is the difference then? In short, the only difference between the two is execution speed and memory size. xrange runs faster and better in terms of memory consumption. why is that the case ? xrange is implemented such that it does not return all elements at once, instead it generates them on demand. If you are curious, this is a separate topic in Python, you can check the following article for more information. To be more specific, the return type of range is a Python list while the return type of xrange is a generator object that can be called on demand.

Tips when to use what

  • For compatible code between Python 2.x and 3.x, use only range
  • To generate large sequences, use xrange
  • If the sequence is not large and iterating over the list multiple times is needed, use range in this case

Summary

Here is a tabular summary…

rangexrange
Python 2.x and 3.xPython 2.x only
range in Python 2.x is not the same as range in Python 3.xxrange in Python 2.x is the same as range in Python 3.x
Generates a sequence of numbers using a listGenerates a sequence of numbers on demand using a generator object
Good for small sequences and/or when iteration is repeated over and over the same listGood for large sequences as it is faster and better memory management
Returns a list objectReturns a generator object

References

Tags:

Add a Comment

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