[Tutor] Difference between range and xrange

Cameron Simpson cs at cskk.id.au
Tue Oct 8 05:11:45 EDT 2019


On 08Oct2019 13:02, Gursimran Maken <gursimran.maken at gmail.com> wrote:
>I would like to know the difference between range and xrange with 
>respect
>to both python2 and python3.

In python2 range() returns a list of values and xrange() is a generator 
which yields those values progressively. So range() (a) consumes enough 
memory to store all the values individually and (b) does not return 
until it has computed and stored all those values. By contrast, xrange() 
is a generator yielding the same values. You get the first value 
immediately, and the values are not stored.

In python3 there's no xrange(), and range() is a generator function 
yields values like xrange() used to in Python 2.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list