You can check if you have an iterator (consumed once next raises a StopIteration exception) against just repeating (maybe repeating several times) using collections.abc module . Here is an example:
from collections.abc import Iterable, Iterator def my_iterator(): yield 1 i = my_iterator() a = [] isinstance(i, Iterator)
What does my_iterator() a Iterator have the __next__ and __iter__ magic methods (and by the way, basically what happens behind the scenes when you call isinstance on collections.abc abstract base class is a test for the presence of certain magic methods).
Note that the iterator is also Iterable , like an empty list (i.e. both have a magic __iter__ method):
isinstance(i, Iterable)
Also note, as Martijn Pieters answer pointed out , that when you use the generic iter() function for both, you get an iterator:
isinstance(iter(my_iterator()), Iterator)
The difference between [] and my_iterator() is that iter(my_iterator()) returns itself as an iterator, while iter([]) creates a new iterator each time.
As MP mentioned in a similar answer, your object above is not an “iterator container”. This is an iterable object, i.e. Iterable. Whether it is “containing” something is not really connected; the concept of addition is represented by the abstract base class Container . A Container can be iterable, but this is optional.
source share