The following example is given by the documentation:
In the statement
for X in Y
, Y must be an iterator or some object for whichiter()
can create an iterator. These two statements are equivalent:for i in iter(obj): print(i) for i in obj: print(i)
According to this same source,
Behind the scenes, the for statement calls
iter()
on the container object. The function returns an iterator object that defines the method__next__()
which accesses elements in the container one at a time. When there are no more elements,__next__()
raises aStopIteration
exception which tells the for loop to terminate.
Considering both cases, when Y is an iterator or some object for which iter() can create an iterator,
- if Y is an iterable (has an
iter()
method), the for statement calls this method and returns an iterator whosenext()
method is used to iterate through each element of Y. I assume this is the second example above. - if Y is an iterator (has both an
iter()
andnext()
method), the for statement still calls theiter()
method, but because it's an iterator, it returns itself
, and thenext()
method is called as usual. I assume this is the first example above.
My question being, is my line of reasoning correct? I don't mind if you point out any misuse of a definition.
CodePudding user response:
See https://docs.python.org/3/library/stdtypes.html#typeiter.
iterator.__iter__()
Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.