Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the range object "not an iterator"? [duplicate]

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 
like image 542
temporary_user_name Avatar asked Feb 15 '14 21:02

temporary_user_name


People also ask

Why is range not an iterator?

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.

Is Range an iterator or iterable?

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).

Which is not a iterator in python?

A list object is not an iterator because it does not have a __next__() method.

Is every iterable an iterator?

Note that every iterator is also an iterable, but not every iterable is an iterator.


Video Answer


1 Answers

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.

like image 68
NPE Avatar answered Oct 10 '22 03:10

NPE