3
Contributors
3
Replies
12
Views
7 Years
Discussion Span
Last Post by Gribouillis
1

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 by Gribouillis: n/a

-1

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

0

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.