Iterators
Aahz
aahz at pythoncraft.com
Fri Oct 16 12:13:10 EDT 2009
In article <Xns9CA687FE4D6F8duncanbooth at 127.0.0.1>,
Duncan Booth <duncan.booth at suttoncourtenay.org.uk> wrote:
>Chris Rebert <clp2 at rebertia.com> wrote:
>>
>> Essentially, file iterators are dumb and don't keep track of where in
>> the file the next line starts, instead relying on their associated
>> file object to keep track of the current position in the file; the
>> iterator's state is little more than a reference to its associated
>> file object. When asked for the "next" line, a file iterator just
>> reads forward to the next newline from the file object's current
>> position, changing the current position as tracked by the file object
>> as a side-effect. Thus, using multiple iterators to the same file
>> object can have the results you're seeing when these side-effects
>> interact.
>
>Nothing 'dumb' or 'smart' about it: it is simply that a file object is
>already an iterator. Trying to create an iterator from an existing iterator
>in Python never duplicates the iterator.
>
>>>> f = open('somefile')
>>>> iter(f) is f
>True
Expanding on that a bit, a file object is an iterator; a list object is
an iterable from which iterators can be created:
>>> L = [1, 2, 3]
>>> i1 = iter(L)
>>> i2 = iter(L)
>>> i1 is i2
False
>>> i1 is L
False
--
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
"To me vi is Zen. To use vi is to practice zen. Every command is a
koan. Profound to the user, unintelligible to the uninitiated. You
discover truth everytime you use it." --reddy at lion.austin.ibm.com
More information about the Python-list
mailing list