An iterable needs to implement an __iter__
method or a __getitem__
method:
An object can be iterated over with for
if it implements __iter__()
or __getitem__()
.
An iterator needs a __iter__
method (that returns self
) and a __next__
method (I'm not 100% sure about the __next__
).
it is true that an iterator always has __iter__
method?
Yes!
This is also documented in the Data model:
object.__iter__(self)
This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container.
Iterator objects also need to implement this method; they are required to return themselves. For more information on iterator objects, see Iterator Types.
(Emphasis mine)
As to your second question:
Is an iterator also an iterable?
Yes, because it has a __iter__
method.
Additional notes
Besides the formal implementation it's easy to check if something is iterable by just checking if iter()
can be called on it:
def is_iterable(something):
try:
iter(something)
except TypeError:
return False
else:
return True
Likewise it's possible to check if something is an iterator by checking if iter()
called on something returns itself:
def is_iterator(something):
try:
return iter(something) is something # it needs to return itself to be an iterator
except TypeError:
return False
But don't use them in development code, these are just for "visualization". Mostly you just iterator over something using for ... in ...
or if you need an iterator you use iterator = iter(...)
and then process the iterator by calling next(iterator)
until it throws a StopIteration
.
self
. – Viridescent__iter__
method and so being iterable in the official sense). There's no good single-word term for "non-iterator iterable", so some folks just use "iterable" for that, even though its not accurate. I elaborated a bit on this topic in a previous answer. – Frederiksen