Perhaps I’ve fallen victim to misinformation on the web, but I think it’s more likely just that I’ve misunderstood something. Based on what I’ve learned so far, range() is a generator, and generators can be used as iterators. However, this code:
myrange = range(10)
print(next(myrange))
gives me this error:
TypeError: 'range' object is not an iterator
What am I missing here? I was expecting this to print 0, and to advance to the next value in myrange. I’m new to Python, so please accept my apologies for the rather basic question, but I couldn’t find a good explanation anywhere else.
rangeis a class of immutable iterable objects. Their iteration behavior can be compared tolists: you can’t callnextdirectly on them; you have to get an iterator by usingiter.So no,
rangeis not a generator.You may be thinking, "why didn’t they make it an iterator"? Well,
ranges have some useful properties that wouldn’t be possible that way:start,stopandstepattributes (since Python 3.3),countandindexmethods and they supportin,lenand__getitem__operations.rangemultiple times.