What does xrange do in python?? And how do I implement a similar function in Python3??

In a terminal:

$ pydoc xrange

class xrange(object)
 |  xrange([start,] stop[, step]) -> xrange object
 |  
 |  Like range(), but instead of returning a list, returns an object that
 |  generates the numbers in the range on demand.  For looping, this is 
 |  slightly faster than range() and more memory efficient.

AN object like xrange(10) implements the iterator protocol: it has a method __iter__ which returns an object with a __next__ method, so you can write

>>> r = xrange(10)
>>> it = iter(r)
>>> next(it)
0
>>> next(it)
1
>>> next(it)
2

# or
>>> for number in r: ...

but the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] is never built.
In python 3, range replaces xrange so that

python 2    |  python 3
------------------------
xrange(10)  |  range(10)
range(10)   |  list(range(10))

If you want a python 3 behavior in python 2, you can write

import sys
if sys.version_info < (3,):
    range = xrange

Edited 6 Years Ago by Gribouillis: n/a

Hi
The xrange is changed to range.
In 3.x range's function is similar xrange.
So just use range instead of xrange.

Hi
The xrange is changed to range.
In 3.x range's function is similar xrange.
So just use range instead of xrange.

This thread is very old, and already solved. Don't revive old threads !

This question has already been answered. Start a new discussion instead.