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?
as you can see from this link - https://docs.python.org/2/library/functions.html#xrange
xrange
will return axrange-object
instead of alist
which is iterable. so you cannot directly call next on it.