0

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?

user2399453
  • 2,930
  • 5
  • 33
  • 60
  • If you can call `next` on something then that necessarily means it has a state. `xrange` objects have no state. – SethMMorton Aug 29 '17 at 05:33
  • Question: If I do `a = xrange(10); print 5 in a`, what would you expect the result of `print list(a)` to be afterwards? – SethMMorton Aug 29 '17 at 05:50

1 Answers1

0

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.

Max
  • 1,283
  • 9
  • 20