iter()
supports different types of objects.
You can pass in either a sequence (supporting length and item access) or an iterable (which produces an iterator by calling obj.__iter__()
) or an iterator (which returns self
from __iter__
).
The Java list.iter()
then is served by list.__iter__()
in Python, but the iter()
function allows for more types. You can customise the behaviour with a __iter__
method but if you implemented a sequence instead, things will still work.
There is also a second form of the function where a callable and a sentinel are passed in:
iter(fileobj.readline, '')
iterates over a file object by calling the readline()
method until it returns an empty string (equal to the second argument, the sentinel).
Then there is the Principle of Least Astonishment argument; iter()
gives the standard library a stable API call to standardise on, just like operators do; no need to look up the documentation of the class to see if it implemented obj.iter()
or obj.iterator()
or obj.get_iterator()
.