I wrote this and expected 0
:
>>> x = range(20) >>> next(x)
Instead I got:
TypeError: 'range' object is not an iterator
But I thought it was a generator?
The initial answer yielded the same thing I initially said to myself: it's an iterable, not an interator. But then, that wouldn't explain why this works, if both are simply generators:
>>> x = (i for i in range(30)) >>> next(x) 0
Python | range() does not return an iterator In python range objects are not iterators. range is a class of a list of immutable objects. The iteration behavior of range is similar to iteration behavior of list in list and range we can not directly call next function. We can call next if we get an iterator using iter.
range returns an iterable, not an iterator. It can make iterators when iteration is necessary. It is not a generator. A generator expression evaluates to an iterator (and hence an iterable as well).
A list object is not an iterator because it does not have a __next__() method.
Note that every iterator is also an iterable, but not every iterable is an iterator.
The range object is iterable. However, it's not an iterator.
To get an iterator, you need to call iter()
first:
>>> r=range(5,15) >>> next(iter(r)) 5 >>> next(iter(r)) 5 >>> next(iter(r)) 5 >>> next(iter(r)) 5 >>> i=iter(r) >>> next(i) 5 >>> next(i) 6 >>> next(i) 7 >>> next(i) 8 >>> iter(r) <range_iterator object at 0x10b0f0630> >>> iter(r) <range_iterator object at 0x10b0f0750> >>> iter(r) <range_iterator object at 0x10b0f0c30>
Edit: But be careful not to call iter()
with every call to next()
. It creates a new iterator at index 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With