xrange vs iterators python

165 views Asked by At

I am a little confused by why I can't treat an xrange() object as an iterator:

In [47]: xr = xrange(1,7)

In [48]: next(xr)
-----------------------------------------------------------------------
----
TypeError                                 Traceback (most recent call 
last)
<ipython-input-48-e71cfa0995ec> in <module>()
 ----> 1 next(xr)

TypeError: xrange object is not an iterator

It works if xrange() is wrapped inside iter(). It also works if I do a for in loop over xr. How does for loop get translated if xr is not an iterator?

EDIT: I saw the other answer that was recommended but its still not clear why the xrange object isn't directly iterable. The other answer mentions that xrange objects are immutable and this is a benefit. But what is the link between being immutable and not being directly iterable? Even an iterable object seems immutable to me so what exactly is the benefit of or reason behind a range object not being directly iterable?

1

There are 1 answers

0
Max On

as you can see from this link - https://docs.python.org/2/library/functions.html#xrange

xrange will return a xrange-object instead of a list which is iterable. so you cannot directly call next on it.