Python’s for statement iterates over the items of any sequence (a list or a string).
But where does the sequence come from in below code?
file=open('filename.txt','r')
for line in file:
print line
Is this related to the __iter__()
method?
Just some quote:
https://docs.python.org/3/glossary.html#term-iterable
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an
__iter__()
or__getitem__()
method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip()
,map()
, ...). When an iterable object is passed as an argument to the built-in functioniter()
, it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and generator.